【问题标题】:How to include milliseconds in a formatted date string?如何在格式化的日期字符串中包含毫秒?
【发布时间】:2011-11-08 14:10:46
【问题描述】:

您好,我正在编写以下代码:

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 位的毫秒数?

谢谢

【问题讨论】:

标签: java android date time


【解决方案1】:

使用以下内容:

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

【讨论】:

  • 请注意,我已将“hh”更改为“HH”,以便以 24 小时格式显示小时。如果需要 12 小时格式,请使用“hh”
  • 虽然此答案在发布时是正确的,但此处使用的类现在已被 java.time 类所取代。
【解决方案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 = 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 类?

【讨论】:

    【解决方案3】:

    尝试使用与SimpleDateFormat相同的格式

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 2020-08-27
      相关资源
      最近更新 更多