Parse String to date with timezone offset intact

后端 未结 1 785
既然无缘
既然无缘 2021-01-26 07:43

We have a client sending date to us in String format as \"2017-06-14T04:00:00-08:00\". We need to convert it to JAVA Date type before working with it.

We ar

相关标签:
1条回答
  • 2021-01-26 08:33

    java.util.Date doesn't store time zone information.

    To retain time zone, use ZonedDateTime or OffsetDateTime (Java 8+).

    Since your date string is ISO 8601, you won't even need to specify a date format.

    ZonedDateTime zdt = ZonedDateTime.parse("2017-06-14T04:00:00-08:00");
    System.out.println(zdt); // prints: 2017-06-14T04:00-08:00
    
    OffsetDateTime odt = OffsetDateTime.parse("2017-06-14T04:00:00-08:00");
    System.out.println(odt); // prints: 2017-06-14T04:00-08:00
    

    For pre-Java 8, use the ThreeTen-Backport:

    ThreeTen-Backport provides a backport of the Java SE 8 date-time classes to Java SE 6 and 7.

    0 讨论(0)
提交回复
热议问题