Java 7 DateFormat 将 UTC 日期解析为本地日期

标签 java java-7 simpledateformat date-format date

您能否告诉我 JDK 7 的日期格式应该是什么来解析日期 2019-06-18T19:04:30.515 UTC 并将其更改为本地日期时间?

最佳答案

java.time

对于 Java 6 和 7,您可以使用 ThreeTen-Backport项目将大多数现代 java.time 功能引入 Java 6 和 Java 7。这意味着您可以避免使用可怕的遗留日期时间类,例如 SimpleDateFormat (已替换)通过DateTimeFormatter)。

parse the date 2019-06-18T19:04:30.515 UTC

首先,我们操作您的输入字符串以完全符合 ISO 8601 。我们用 Z 替换 SPACE 和“UTC”,发音为“Zulu”。

String input = "2019-06-18T19:04:30.515 UTC".replace( " UTC" , "Z" ) ;
Instant instant = Instant.parse( input ) ;

and change it to local date time?

要调整为 UTC 的另一个时区,请应用 ZoneId 来获取 ZonedDateTime

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;  // Or "Europe/Berlin" etc. 
ZonedDateTime zdt = instant.atZone( z ) ;

要生成表示针对用户的人类语言和文化规范本地化的日期时间值的字符串,请使用 DateTimeFormatter.ofLocalizedDateTime

关于Java 7 DateFormat 将 UTC 日期解析为本地日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56655600/

相关文章:

java - Tomcat内存消耗大于heap + permgen空间

java - 如何访问 strings.xml 中的 java 变量

java - NoSuchMethodError : com. google.common.util.concurrent.MoreExecutors.directExecutor

java - XMLInputFactory 是线程安全的吗?

jsf-2 - 丰富的 :calendar ignored format pattern for the day of the week after selecting

java - 如果我的测试中有验证,那么期望是多余的吗?

Java 文件不存在,但 File.getAbsoluteFile() 存在

java - NetBeans 中 Java 7 的编译问题

java - SimpleDateFormat.parse 生成不一致的结果

java - 如何解析具有个位数偏移量的时区? "Wed Dec 31 00:00:00 GMT-8 1969"