IST to EST Time Conversion In Java

梦想与她 提交于 2019-12-02 11:06:22

The Date class is time-zone agnostic. Basically, it is always based on GMT although when it is printed it uses the current system time zone to adjust it.

However, Calendar is time-zone specific. See Calendar.setTimeZone().

Consider:

   Calendar cal = new GregorianCalendar();
   cal.setTimeZone(TimeZone.getTimeZone("America/New_York"));
   cal.setTime(new Date());

Should you add z for time-zone pattern in your SimpleDateFormat pattern?

So, it should be DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"). I changed your code like this:

public static void main(String[] args) throws ParseException {
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
    dateTimeFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
    Date date = new Date();

    System.out.println(dateTimeFormat.format(date)); // this print IST Timezone

    DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
    timeFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));

    String estTime = timeFormat.format(date);
    date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z", Locale.ENGLISH).parse(estTime);

    System.out.println(timeFormat.format(date)); // this print EDT Timezone currently (on March)
}

In last print statement, current date format is printed with EDT Timezone (Eastern Daylight Time). Maybe because of this.

Basil Bourque

The correct answer by John B explains that java.util.Date seems to have a time zone but does not. Its toString method applies your JVM's default time zone when generating the string representation.

That is one of many reasons to avoid java.util.Date and .Calendar classes bundled with Java. Avoid them. Instead use either Joda-Time or the java.time package built into Java 8 (inspired by Joda-Time, defined by JSR 310).

Here is some example code in Joda-Time 2.3.

String input = "01/02/2014 12:34:56";
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm:ss" );
DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = formatterInput.withZone( timeZoneIndia ).parseDateTime( input );

DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );
DateTime dateTimeNewYork = dateTimeIndia.withZone( timeZoneNewYork );

DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC );

Dump to console…

System.out.println( "input: " + input );
System.out.println( "dateTimeIndia: " + dateTimeIndia );
System.out.println( "dateTimeNewYork: " + dateTimeNewYork );
System.out.println( "dateTimeUtc: " + dateTimeUtc );

When run…

input: 01/02/2014 12:34:56
dateTimeIndia: 2014-01-02T12:34:56.000+05:30
dateTimeNewYork: 2014-01-02T02:04:56.000-05:00
dateTimeUtc: 2014-01-02T07:04:56.000Z
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!