获得ISO 8601格式的当前时刻UTC的最优雅的方式是什么?它看起来应该像:2010-10-12 t8: 50z。

例子:

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

当前回答

private static String getCurrentDateIso()
{
    // Returns the current date with the same format as Javascript's new Date().toJSON(), ISO 8601
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return dateFormat.format(new Date());
}

其他回答

Apache common -lang3中的DateFormatUtils有一些有用的常量,例如:ISO_DATETIME_FORMAT

对于ISO 8601,您可以使用Java的SimpleDateFormat,格式如下:yyyy-MM-dd'T'HH:mm:ssXXX。

示例代码:(列出所有可用的时区)

for (String timeZone : TimeZone.getAvailableIDs())
{
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
    String formatted = dateFormat.format(new Date());
    System.out.print(formatted);

    if (formatted.endsWith("Z"))
    {
        // These time zone's have offset of '0' from GMT.
        System.out.print("\t(" + timeZone + ")");
    }

    System.out.println();
}

你可以用:

TimeZone.getDefault()

虚拟机默认时区。更多的在这里

你可能会注意到,很少有时区的日期时间是以Z结尾的。这些时区与GMT的偏移量为“0”。

更多信息可以在这里找到。

对于默认时区不是UTC的系统:

TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());

如果经常需要,可以将SimpleDateFormat实例声明为全局常量,但要注意该类不是线程安全的。如果被多个线程并发访问,则必须进行同步。

编辑:我更喜欢Joda时间,如果做许多不同的时间/日期操作… EDIT2:更正:setTimeZone不接受字符串(由Paul更正)

他们应该添加一些简单的方法来从日期到即时,还有一个叫做toISO8601的方法,这是很多人都在寻找的。 作为对其他答案的补充,从java.util.Date到ISO 8601格式:

Instant.ofEpochMilli(date.getTime()).toString();

当使用自动补全时,它是不可见的,但是: java.time.Instant.toString ():

使用ISO-8601表示该时刻的字符串

private static String getCurrentDateIso()
{
    // Returns the current date with the same format as Javascript's new Date().toJSON(), ISO 8601
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return dateFormat.format(new Date());
}