IST to EST Time Conversion In Java

后端 未结 3 938
醉话见心
醉话见心 2021-01-27 09:20

I have a Date field in Java in IST Time. I want to convert the same to EST Time and the output should be as a Date Type only. I am able to accomplish the same using the below pi

3条回答
  •  醉话见心
    2021-01-27 10:07

    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
    

提交回复
热议问题