6

Please suggest a way to print a date in EST.

public Date convertToEST(Date date)
{
     // some code here
}

If I pass in a date in IST, the method should return that date in EST.

mtk
  • 13,221
  • 16
  • 72
  • 112
buttowski
  • 4,657
  • 8
  • 27
  • 33

5 Answers5

6

You need the following

Date date = new Date();  

DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");

// Set the formatter to use a different timezone  
formatter.setTimeZone(TimeZone.getTimeZone("EST"));  

// Prints the date in the EST timezone  
System.out.println(formatter.format(date));  

To make return the method a Date object, you will need as shown below

public static Date convertToEST(Date date) throws ParseException {
    DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
    formatter.setTimeZone(TimeZone.getTimeZone("EST"));
    return formatter.parse((formatter.format(date)));
}

Javadoc- DateFormat.format, DateFormat.parse

mtk
  • 13,221
  • 16
  • 72
  • 112
  • 2
    in my console am still getting it as IST dude wats the prob ? – buttowski Dec 25 '12 at 12:36
  • 1
    when i print just as String "formatter.format(date)" it is fine am getting it in EST. but, when i print system.out.println(formatter.parse(formatter.format(date)))); am getting it as IST – buttowski Dec 25 '12 at 12:42
  • i think i should change my workstation(PC) time zone to EST am getting as expected but i want do this without changing my workstation time zone – buttowski Dec 25 '12 at 12:52
  • `GregorianCalendar.getInstance(TimeZone.getTimeZone("PST")).getTime()` does not work. Any idea? – Mercenary Oct 17 '14 at 11:43
  • 3
    This code does not return the correct EST time. I tried it – Coder17 Jun 30 '17 at 10:52
6

tl;dr

myJavaUtilDate     // Avoid the troublesome legacy date-time classes. 
    .toInstant()   // Convert from legacy class to modern class `Instant`, always in UTC by definition.
    .atZone(       // Adjust into a time zone. Same moment, different wall-clock time.
        ZoneId.of( “America/New_York” )  // Never use “EST”/“IST” pseudo-zones. Use proper continent/region names. 
    )              // Yields a `ZonedDateTime` object. 

Use Instant, not Date

The other Answers use troublesome old legacy date-time classes. Those were supplanted years ago by the java.time classes. Forget about java.util.Date, a poorly-designed mess of a class.

If I pass in a date in IST,

Don’t!

Learn to think, work, exchange, and log in UTC values. Forget about your own parochial time zone while on the job as programmer or administrator. Think of UTC as the One True Time, all other zones are but mere variations.

The building block in java.time is Instant class. This class represents a moment, a point on the timeline in UTC. Internally represented as a count of seconds plus nanoseconds since the start of 1970 in UTC.

Instant instant = Instant.now() ;  // Capture current moment in UTC.

Such Instant objects are what you should be passing around your code, generally speaking. Adjust into a time zone only when required by your business logic or user-interface.

Never use the 3-4 letter pseudo-zones seen frequently in the media, such as “IST” or “EST”. Instead, use proper time zone names defined as continent/region such as Europe/Paris or Asia/Kolkata or America/New_York.

ZoneId z = ZoneId.of( “America/New_York” ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

If you must serialize to text to exchange date-time values, use the standard ISO 8601 formats. These are used by default in java.time toString and parse methods.

To generate Strings in other formats, see the DateTimeFormatter class.

To inter-operate with old code not yet updated to java.time, call on new conversion methods added to the old classes.

A Date represents a moment in UTC, and so it maps directly to Instant.

Instant instant = myJavaUtilDate.toInstant() ;

And…

java.util.Date myJavaUtilDate = java.util.Date.from( instant ) ;

The legacy GregorianCalendar maps to the modern ZonedDateTime.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • > "Never use “EST”/“IST” pseudo-zones" why? – Samir Dec 29 '20 at 19:06
  • 2
    @Samir Because they are not real time zone names. And they are not standardized. And they are not unique: Does `IST` mean *Irish Standard Time* or *India Standard Time*? Yes, both. And both are invalid when Daylight Saving Time (DST) is in effect. Instead use `Europe/Dublin` or `Asia/Kolkata`. – Basil Bourque Dec 29 '20 at 21:11
4

The idea of "the method should return that date in EST" is wrong. Date is only a holder of milliseconds since January 1, 1970, 00:00:00 GMT. It has nothing to do with the time zone.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • system.out.println(new Date()); i get something like a MMM dd HH:mm:ss IST yyyy i just want this in EST – buttowski Dec 25 '12 at 11:52
2

Changing time zones in java

public class TimeZoneSample {
    public static void main(String[] args) throws ParseException {

        // I am in IST time Zone (Its ID is Asia/Calcutta or ITS)
        System.out.println(TimeZone.getDefault());
        // I get Indian Time printed
        System.out.println(new Date());
        System.out.println("-------------------");
        // I am setting the time zone to China
        TimeZone.setDefault(TimeZone.getTimeZone("CTT"));
        // Now my default time zone is in China
        System.out.println(TimeZone.getDefault());
        // I get Chian Time printed
        System.out.println(new Date());
        System.out.println("-------------------");
        // I am setting the time zone to EST
        TimeZone.setDefault(TimeZone.getTimeZone("EST"));
        // Now my default time zone is in EST
        System.out.println(TimeZone.getDefault());
        // I get Eastern Time printed
        System.out.println(new Date());

    }

}

console output

sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
Wed Dec 26 10:22:25 IST 2012
-------------------
sun.util.calendar.ZoneInfo[id="CTT",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null]
Wed Dec 26 12:52:25 CST 2012
-------------------
sun.util.calendar.ZoneInfo[id="EST",offset=-18000000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Tue Dec 25 23:52:25 EST 2012
om39a
  • 1,406
  • 4
  • 20
  • 39
  • this what i expected thanks a lot buddy :) This helped me a lot – buttowski Dec 26 '12 at 05:26
  • 1
    -04:00 = PRT (-4a Puerto Rico and US Virgin Islands Time). Ref this link on [different time zone](http://support.novell.com/docs/Tids/InfoDocument/2908587.html) – om39a Dec 26 '12 at 06:07
  • `GregorianCalendar.getInstance(TimeZone.getTimeZone("PST")).getTime()` does not work! Any ideas? – Mercenary Oct 17 '14 at 11:43
  • EST time is coming one hour less. Current est time is 9.22 am may 19. But it is printing one hour less in my console. Probably daylight time issue. How to overcome this? any idea? – Senthil May 19 '20 at 13:23
1
DateFormat requiredDateFormat = new SimpleDateFormat("hh:mm a zzz, EEE MMMM dd,yyyy");
requiredDateFormat.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
String date = requiredDateFormat.format(new Date());
System.out.println(date);

Console Output: 06:25 AM EST, Tue February 13,2018

Aakash Goplani
  • 1,150
  • 1
  • 19
  • 36
  • 1
    These troublesome confusing date-time classes are obsolete, supplanted by the *java.time* classes years ago. Their use is ill-advised in 2018. – Basil Bourque Feb 13 '18 at 18:08
  • @BasilBourque Even in 2020, Android SDK still didn't get the java.time package added in Java 8. It's only present on Nougat and later, while most apps still have to support Lollipop at the least. – Sri Harsha Chilakapati Nov 10 '20 at 20:10
  • @SriHarshaChilakapati No, your comment is not up-to-date. The API desugaring ability in latest Android tools bring a subset of *java.time* and other features to older Android versions before 26. See links at end of [my Answer](https://stackoverflow.com/a/48772823/642706) on this page. There is no need to ever again use the terrible legacy date-time classes such as `Date` and `SimpleDateFormat`. – Basil Bourque Nov 11 '20 at 00:18