如何在格式化的日期字符串中包含毫秒?tl;博士InstantZonedDateTimeDateTimeFormatter关于 java.time

2022-09-04 01:13:39

嗨,我正在编写以下内容:

String sph=(String) android.text.format.DateFormat.format("yyyy-MM-dd_hh-mm-ss_SSS", new java.util.Date()); 

我想要当前日期和时间以及毫秒

它给我的是:

2011-09-01_09-55-03-SSS

SSS 不会转换回毫秒...

有谁知道为什么以及应该把毫秒放在3个位置是什么?

谢谢


答案 1

使用以下命令:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SSS");
String dateString = formatter.format(new java.util.Date());

答案 2

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.now();
String output = instant.toString();

该 toString 方法使用 DateTimeFormatter.ISO_INSTANT 格式化程序,该格式化程序以小数形式打印 0、3、6 或 9 位数字,根据需要根据需要打印适合实际数据值的数字。

在Java 8中,当前时刻最多只能捕获毫秒,但Java 9中时钟的新实现可能会捕获高达纳秒。因此,如果这是您的要求,请截断到毫秒。通过 ChronoUnit.MILLIS 中实现的时间单位指定所需的截断。

Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS );

ZonedDateTime

如果要指定时区,请应用 a 以获取 .ZoneIdZonedDateTime

Instant instant = Instant.now();

瞬视(): 2018-08-26T19:43:24.895621Z

Instant instantTruncated = instant.truncatedTo( ChronoUnit.MILLIS );

瞬切齿状至字符串(): 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[美国/蒙特利尔]

同样,如果需要其他格式,请在“堆栈溢出”中搜索 。DateTimeFormatter

DateTimeFormatter

如果要强制三位数持续毫秒,即使值全部为零,也可以使用 class 指定自定义格式设置模式。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 及更高版本中。这些类取代了麻烦的旧日期时间类,如java.util.DateCalendarSimpleDateFormat

Joda-Time 项目现在处于维护模式,建议迁移到 java.time 类。

要了解更多信息,请参阅 Oracle 教程。搜索 Stack Overflow 以获取许多示例和解释。规格是JSR 310

您可以直接与数据库交换 java.time 对象。使用符合 JDBC 4.2 或更高版本的 JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

从哪里获取 java.time 类?