tl;博士
Instant // Represent a moment in UTC.
.ofEpochSecond( mnSeconds ) // Determine a moment from a count of whole seconds since the Unix epoch of the first moment of 1970 in UTC (1970-01-01T00:00Z).
.plusNanos( mnNanoseconds ) // Add on a fractional second as a count of nanoseconds. Returns another `Instant` object, per Immutable Objects pattern.
.toString() // Generate text representing this `Instant` object in standard ISO 8601 format.
.replace( "T" , " " ) // Replace the `T` in the middle with a SPACE.
.replace "Z" , "" ) // Remove the `Z` on the end (indicating UTC).
java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了旧的麻烦的日期时间类,例如java.util.Date、.Calendar、java.text.SimpleDateFormat、java.sql.Date 等。 Joda-Time 团队还建议迁移到 java.time。
Instant
Instant 类代表 UTC 时间轴上的一个时刻,分辨率高达纳秒。
long mnSeconds = … ;
long mnNanoseconds = … ;
Instant instant = Instant.ofEpochSecond( mnSeconds ).plusNanos( mnNanoseconds );
或者将两个数字作为两个参数传递给of。不同的语法,相同的结果。
Instant instant = Instant.ofEpochSecond( mnSeconds , mnNanoseconds );
要获取表示此日期时间值的字符串,请调用 Instant::toString。
String output = instant.toString();
您将获得一个值,例如2011-12-03T10:15:30.987654321Z,标准ISO 8601 格式。如果您愿意,请将T 替换为空格。对于其他格式,请搜索 Stack Overflow 以了解 DateTimeFormatter。
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。