我的 Web 应用程序以 13 位数字形式返回日期,例如1475166540000.
如何将其格式化为要在 JSON 响应中返回的正确日期。在我的函数中,它只返回整个 DTO。
Instant.ofEpochMilli( 1_475_166_540_000L )
.toString()
Run Code Online (Sandbox Code Playgroud)
或者…
Instant.ofEpochMilli( Long.parseLong( "1475166540000" ) )
.toString()
Run Code Online (Sandbox Code Playgroud)
AnInstant代表 UTC 中的一个时刻,分辨率为纳秒。
该类可以从 UTC 中 1970 年第一个时刻的纪元参考 1970-01-01T00:00Z 解析毫秒计数。
Instant instant = Instant.ofEpochMilli( 1_475_166_540_000L ) ;
Run Code Online (Sandbox Code Playgroud)
顺便说一下,对于整秒的计数也是如此Instant.ofEpochSecond( mySeconds )。
如果输入是 a String,则解析为 a long。
Instant instant = Instant.ofEpochMilli( Long.parseLong( "1475166540000" ) ) ;
Run Code Online (Sandbox Code Playgroud)
要生成标准ISO 8601格式的字符串,请调用toString.
String output = instant.toString() ;
Run Code Online (Sandbox Code Playgroud)
2016-09-29T16:29:00Z
在Z上到底是短期的“祖鲁”和手段UTC。
如何将其格式化为正确的日期
没有所谓的“适当的日期”。每种文化都有自己的文本显示日期时间值的方式。
对于本地化显示给用户,使用DateTimeFormatter及其ofLocalized…方法。
String output = instant.atZone( ZoneId.of( "Africa/Tunis" ) ).format( DateTimeFormatter.ofLocalizedDateTime?( FormatStyle.FULL ).withLocale( Locale.JAPAN ) ) ; // Use Japanese formatting to display a moment in Tunisia wall-clock time.
Run Code Online (Sandbox Code Playgroud)
2016?9?29???? 17?29?00??????????
要在 JSON 等系统之间交换数据,请仅使用标准 ISO 8601 格式。它们是实用的,旨在明确且易于机器解析,并且易于跨文化的人类阅读。Java 内置的java.time类在解析/生成字符串时默认使用这些标准格式。所以不需要指定格式模式。
String output = instant.toString() ;
Run Code Online (Sandbox Code Playgroud)
2016-09-29T16:29:00Z
Instant instant = Instant.parse( "2016-09-29T16:29:00Z" ) ;
long millisSinceEpoch = instant.toEpochMilli() ;
Run Code Online (Sandbox Code Playgroud)
1475166540000
永远不要使用示例代码中看到的麻烦的 Date/Calendar类。它们现在是遗留的,完全被java.time类取代。
要与尚未更新为 java.time 的旧代码进行互操作,您可以来回转换。调用添加到旧类的新转换方法。
Date d = Date.from( instant ) ; // Don’t do this unless forced to inter-operate with old code not yet updated to java.time classes.
Run Code Online (Sandbox Code Playgroud)
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat。
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。Hibernate 5 & JPA 2.2 支持java.time。java.sql.*
从哪里获得 java.time 类?
| 归档时间: |
|
| 查看次数: |
3992 次 |
| 最近记录: |