java 如何在格式化的日期字符串中包含毫秒?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7273929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:23:07  来源:igfitidea点击:

How to include milliseconds in a formatted date string?

javaandroiddatetime

提问by Keith

Hi I am coding the following:

嗨,我正在编写以下代码:

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

I want the current date and time and milliseconds

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

what it gives me is:

它给我的是:

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

The SSS is not converting back to milliseconds...

SSS 不会转换回毫秒...

Does anyone know why and what should it be to get the milliseconds in 3 position?

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

Thanks

谢谢

回答by Idolon

Use the following:

使用以下内容:

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

回答by Basil Bourque

tl;dr

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

2018-08-26_15-43-24-895

Instant

Instant

You are using troublesome old legacy date-time classes. Instead use the java.time classes.

您正在使用麻烦的旧式日期时间类。而是使用 java.time 类。

If you want the date-time in UTC, use the Instantclass. This class holds nanosecond resolution, more than enough for milliseconds.

如果您想要 UTC 中的日期时间,请使用Instant该类。这个类拥有纳秒级的分辨率,对于毫秒来说已经足够了。

Instant instant = Instant.now();
String output = instant.toString();

That toStringmethod uses the DateTimeFormatter.ISO_INSTANTformatter which prints 0, 3, 6, or 9 digits in the decimal fraction, as many as needed appropriate to the actual data value.

toString方法使用DateTimeFormatter.ISO_INSTANT格式化程序打印十进制小数中的 0、3、6 或 9 位数字,根据实际数据值的需要而定。

In Java 8 the current moment is captured only up to milliseconds but a new implementation of Clockin Java 9 may capture up to nanoseconds. So truncate to milliseconds if that is your requirement. Specify your desired truncation by a TemporalUnitas implemented in ChronoUnit.MILLIS.

在 Java 8 中,当前时刻最多只能捕获到毫秒,但Clock在 Java 9 中的新实现可能会捕获到纳秒。如果这是您的要求,请截断到毫秒。指定所需的截断,TemporalUnit如在 中实现的ChronoUnit.MILLIS

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

ZonedDateTime

ZonedDateTime

If you want a specify time zone, apply a ZoneIdto get a ZonedDateTime.

如果您想要指定时区,请应用 aZoneId以获取ZonedDateTime.

Instant instant = Instant.now();

instant.toString(): 2018-08-26T19:43:24.895621Z

Instant.toString(): 2018-08-26T19:43:24.895621Z

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

instantTruncated.toString(): 2018-08-26T19:43:24.895Z

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[America/Montreal]

2018-08-26T15:43:24.895621-04:00[美国/蒙特利尔]

Again if you want other formats, search Stack Overflow for DateTimeFormatter.

同样,如果您需要其他格式,请在 Stack Overflow 中搜索DateTimeFormatter.

DateTimeFormatter

DateTimeFormatter

If you want to force three digits for milliseconds, even if the value is all zeros, specify a custom formatting pattern using DateTimeFormatterclass.

如果您想在毫秒内强制使用三位数字,即使该值全为零,请使用DateTimeFormatterclass指定自定义格式模式。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd_HH-mm-ss-SSS" ) ;
String output = zdt.format( f ) ;

2018-08-26_15-43-24-895

2018-08-26_15-43-24-895



About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

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

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

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

Where to obtain the java.time classes?

从哪里获得 java.time 类?

回答by Bozho

Try using the same format with SimpleDateFormat

尝试使用相同的格式 SimpleDateFormat