tl;博士
ZonedDateTime // Represent a moment in the wall-clock time used by the people of a certain region (a time zone).
.now() // Capture current moment. Better to pass optional argument for `ZoneId` (time zone). Returns a `ZonedDateTime` object.
.format( // Generate a `String` with text in a custom formatting pattern.
DateTimeFormatter.ofPattern( "uuuu-MM-dd_HH-mm-ss-SSS" )
) // Returns a `String` object.
2018-08-26_15-43-24-895
Instant
您正在使用麻烦的旧旧日期时间类。而是使用 java.time 类。
如果您想要 UTC 日期时间,请使用 Instant 类。这个类拥有纳秒级的分辨率,对于毫秒级来说绰绰有余。
Instant instant = Instant.now();
String output = instant.toString();
toString 方法使用DateTimeFormatter.ISO_INSTANT 格式化程序,它在小数部分中打印 0、3、6 或 9 位数字,根据实际数据值的需要而定。
在 Java 8 中,当前时刻最多只能捕获几毫秒,但 Java 9 中 Clock 的新实现可能最多捕获 nanoseconds。因此,如果这是您的要求,请截断到毫秒。用 TemporalUnit 指定您想要的截断,如在 ChronoUnit.MILLIS 中实现的那样。
Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS );
ZonedDateTime
如果您想要指定时区,请应用ZoneId 以获取ZonedDateTime。
Instant instant = Instant.now();
instant.toString(): 2018-08-26T19:43:24.895621Z
Instant instantTruncated = instant.truncatedTo( ChronoUnit.MILLIS );
instantTruncated.toString(): 2018-08-26T19:43:24.895Z
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );
String output = zdt.toString();
2018-08-26T15:43:24.895621-04:00[美国/蒙特利尔]
同样,如果您想要其他格式,请在 Stack Overflow 中搜索 DateTimeFormatter。
DateTimeFormatter
如果您想强制三位数表示毫秒,即使值全为零,请使用 DateTimeFormatter 类指定自定义格式模式。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd_HH-mm-ss-SSS" ) ;
String output = zdt.format( f ) ;
2018-08-26_15-43-24-895
关于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 类?