如何获取ISO 8601格式的当前时刻,包括日期,小时和分钟?Java 8 Native

2022-08-31 04:40:39

获得当前时刻UTC的ISO 8601格式演示的最优雅方式是什么?它应如下所示:。2010-10-12T08:50Z

例:

String d = DateFormat.getDateTimeInstance(DateFormat.ISO_8601).format(date);
``

答案 1

使用 SimpleDateFormat 设置所需的任何 Date 对象的格式:

TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());

使用如上所示的将格式化当前时间。new Date()


答案 2

Java 8 Native

java.time从Java 8开始就使它变得简单。和线程安全。

ZonedDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ISO_INSTANT )

结果:2015-04-14T11:07:36.639Z

您可能想使用更轻的或,但它们缺少格式化程序支持或时区数据。开箱即用。TemporalInstantLocalDateTimeZonedDateTime

通过调整或链接ZonedDateTimeDateTimeFormatter的选项/操作,您可以在一定程度上轻松控制时区精度

ZonedDateTime.now( ZoneId.of( "Europe/Paris" ) )
             .truncatedTo( ChronoUnit.MINUTES )
             .format( DateTimeFormatter.ISO_DATE_TIME )

结果:2015-04-14T11:07:00+01:00[Europe/Paris]

优化的要求(如删除秒部分)仍必须由自定义格式或自定义后处理来满足。

.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // 2015-04-14T11:07:00
.format( DateTimeFormatter.ISO_LOCAL_DATE ) // 2015-04-14
.format( DateTimeFormatter.ISO_LOCAL_TIME ) // 11:07:00
.format( DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm" ) ) // 2015-04-14 11:07

对于Java 6和7,你可以考虑java.time的反向端口,比如ThreeTen-Backport,它也有一个Android端口。两者都比Joda轻,并且从Joda的经验中吸取了教训 - 特别是考虑到java.time是由Joda的作者设计的。


推荐