欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何获取具有日期,小时和分钟的ISO 8601格式的当前时刻?

程序员文章站 2024-01-14 22:08:22
...

本文翻译自:How to get current moment in ISO 8601 format with date, hour, and minute?

What is the most elegant way to get ISO 8601 formatted presentation of current moment, UTC? 获得UTC当前时刻的ISO 8601格式表示的最优雅方法是什么? It should look like: 2010-10-12T08:50Z . 它应该看起来像: 2010-10-12T08:50Z

Example: 例:

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

#1楼

参考:https://stackoom.com/question/GQJY/如何获取具有日期-小时和分钟的ISO-格式的当前时刻


#2楼

If you don't want to include Jodatime (as nice as it is) 如果您不想包括Jodatime(尽管如此)

javax.xml.bind.DatatypeConverter.printDateTime(
    Calendar.getInstance(TimeZone.getTimeZone("UTC"))
);

which returns a string of: 返回一个字符串:

2012-07-10T16:02:48.440Z

which is slightly different to the original request but is still ISO-8601. 与原始要求略有不同,但仍为ISO-8601。


#3楼

Here's a whole class optimized so that invoking "now()" doesn't do anything more that it has to do. 这是一个优化的整个类,因此,调用“ now()”不会做更多的事情。

public class Iso8601Util
{
    private static TimeZone tz = TimeZone.getTimeZone("UTC");
    private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");

    static
    {
        df.setTimeZone(tz);
    }

    public static String now()
    {
        return df.format(new Date());
    }
}

#4楼

Apache commons-lang3 DateFormatUtils具有有用的常量,例如: DateFormatUtils.ISO_DATETIME_FORMAT


#5楼

ISO 8601 may contains seconds see http://en.wikipedia.org/wiki/ISO_8601#Times ISO 8601可能包含秒数,请参见http://en.wikipedia.org/wiki/ISO_8601#Times

so the code should be 所以代码应该是

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

#6楼

For Java version 7 对于Java版本7

You can follow Oracle documentation: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html 您可以遵循Oracle文档: http : //docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

X - is used for ISO 8601 time zone X-用于ISO 8601时区

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

System.out.println(nowAsISO);

DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
//nowAsISO = "2013-05-31T00:00:00Z";
Date finalResult = df1.parse(nowAsISO);

System.out.println(finalResult);
相关标签: java

上一篇: mysql分表的三种方法

下一篇: