Java Current Date/Time displays 1 hour ahead that original time

前端 未结 2 1855
有刺的猬
有刺的猬 2020-12-20 02:47

When I try to print the current date and time using Calender instance, the result I get is 1 hour ahead from the actual time.

I am working in remote machine which r

2条回答
  •  星月不相逢
    2020-12-20 03:07

    Avoid 3-Letter Time Zone

    Never use the 3-letter time zone codes. They are neither standardized nor unique. Your "EST" can mean at least these:

    • Eastern Standard Time (USA)
    • Eastern Standard Time (Australia)
    • Eastern Brazil Standard Time

    Use time zone names.

    Avoid j.u.Date/Calendar

    You have discovered one of the many reasons to avoid using java.util.Date & java.util.Calendar classes bundled with Java: A Date instance has no time zone information yet its toString method confusingly renders a string based on your Java environment's default time zone.

    Use Joda-Time

    Use a competent date-time library. In Java that means either Joda-Time, or in Java 8, the new java.time.* classes (inspired by Joda-Time).

    Example code…

    // Default time zone
    DateTime dateTime_MyDefaultTimeZone = new DateTime();
    
    // Specific time zone. If by "EST" you meant east coast of United States, use a name such as New York.
    DateTimeZone timeZone = DateTimeZone.forID( "America/New_York" );
    DateTime dateTime_EastCoastUS = new DateTime( timeZone );
    

    Dump to console…

    System.out.println( "dateTime_MyDefaultTimeZone: " + dateTime_MyDefaultTimeZone );
    System.out.println( "dateTime_EastCoastUS: " + dateTime_EastCoastUS );
    System.out.println( "date-time in UTC: " + dateTime_EastCoastUS.toDateTime( DateTimeZone.UTC ) );
    

    When run…

    dateTime_MyDefaultTimeZone: 2013-12-28T18:51:18.485-08:00
    dateTime_EastCoastUS: 2013-12-28T21:51:18.522-05:00
    date-time in UTC: 2013-12-29T02:51:18.522Z
    

提交回复
热议问题