如何在ISO 8601格式中以日期、时间和分钟来获取当前时刻?

时间:2023-02-09 20:24:09

What is the most elegant way to get ISO 8601 formatted presentation of current moment, UTC? It should look like: 2010-10-12T08:50Z.

要获得当前时刻(UTC)的ISO 8601格式化表示,最优雅的方式是什么?应该是:2010-10-12T08:50Z。

21 个解决方案

#1


211  

Use SimpleDateFormat to format any Date object you want:

使用SimpleDateFormat设置您想要的任何日期对象:

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());

Using a new Date() as shown above will format the current time.

使用上面所示的新日期()将格式化当前时间。

#2


201  

For systems where the default Time Zone is not UTC:

对于默认时区不是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());

The SimpleDateFormat instance may be declared as a global constant if needed frequently, but beware that this class is not thread-safe. It must be synchronized if accessed concurrently by multiple threads.

如果经常需要,SimpleDateFormat实例可能被声明为全局常量,但是要注意这个类不是线程安全的。如果由多个线程同时访问,则必须对其进行同步。

EDIT: I would prefer Joda Time if doing many different Times/Date manipulations...
EDIT2: corrected: setTimeZone does not accept a String (corrected by Paul)

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

#3


109  

Java 8:

Java 8:

thisMoment = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX")
                              .withZone(ZoneOffset.UTC)
                              .format(Instant.now());

Pre Java 8:

以前的Java 8:

thisMoment = String.format("%tFT%<tRZ",
                           Calendar.getInstance(TimeZone.getTimeZone("Z")));

From the docs:

从文档:

'R'    Time formatted for the 24-hour clock as "%tH:%tM"
'F'    ISO 8601 complete date formatted as "%tY-%tm-%td".

24小时时钟的'R'时间格式为' %tH:%tM ' ' ' 'F' ISO 8601完整日期格式为' %tY-% tM -%td '。

#4


89  

Java 8 Native

java.time makes it simple since Java 8. And thread safe.

java。自Java 8以来,时间使它变得简单。和线程安全的。

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

Result: 2015-04-14T11:07:36.639Z

结果:2015 - 04 - 14 - t11:07:36.639z

You may be tempted to use lighter Temporal such as Instant or LocalDateTime, but they lacks formatter support or time zone data. Only ZonedDateTime works out of the box.

您可能倾向于使用较轻的时态,例如Instant或LocalDateTime,但它们缺乏格式化程序支持或时区数据。只有ZonedDateTime可以在这个框中工作。

By tuning or chaining the options / operations of ZonedDateTime and DateTimeFormatter, you can easily control the timezone and precision, to a certain degree:

通过调优或链接ZonedDateTime和DateTimeFormatter的选项/操作,您可以轻松地控制时区和精度,在一定程度上:

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

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

结果:2015 - 04 - 14 - t11:07:00 + 01:00(欧洲/巴黎)

Refined requirements, such as removing the seconds part, must still be served by custom formats or custom post process.

改进的需求,例如删除秒部分,仍然必须使用自定义格式或自定义post过程。

.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

For Java 6 & 7, you may consider back-ports of java.time such as ThreeTen-Backport, which also has an Android port. Both are lighter than Joda, and has learned from Joda's experience - esp. considering that java.time is designed by Joda's author.

对于Java 6和7,您可以考虑Java的后端端口。时间,比如3 - backport,它也有一个Android端口。两者都比Joda轻,并且从Joda的经验中学到了很多——尤其是考虑到java。时间是由Joda的作者设计的。

#5


25  

use JodaTime

使用JodaTime

The ISO 8601 calendar system is the default implementation within Joda-Time

ISO 8601日历系统是Joda-Time内的默认实现

Here is the doc for JodaTime Formatter

这是JodaTime Formatter的博士

Edit:

编辑:

If you don't want to add or if you don't see value of adding above library you could just use in built SimpleDateFormat class to format the Date to required ISO format

如果您不想添加,或者您没有看到添加上述库的价值,您可以使用build SimpleDateFormat类将日期格式化为所需的ISO格式

as suggested by @Joachim Sauer

正如@Joachim Sauer所建议的那样

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
String nowAsString = df.format(new Date());

#6


20  

DateFormatUtils from Apache commons-lang3 have useful constants, for example: DateFormatUtils.ISO_DATETIME_FORMAT

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

#7


19  

As of Java 8 you can simply do:

从Java 8开始,你可以简单地做到:

Instant.now().toString();

From the java.time.Instant docs:

从java.time。即时文档:

now

public static Instant now()

公共静态即时现在()

Obtains the current instant from the system clock.

从系统时钟获取当前瞬间。

This will query the system UTC clock to obtain the current instant.

这将查询系统UTC时钟以获得当前的即时。

 

 

toString

public String toString()

公共字符串toString()

A string representation of this instant using ISO-8601 representation.

使用ISO-8601表示的字符串表示。

The format used is the same as DateTimeFormatter.ISO_INSTANT.

所使用的格式与datetimeformat . iso_instant相同。

#8


18  

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。

#9


13  

ISO 8601 may contains seconds see http://en.wikipedia.org/wiki/ISO_8601#Times

ISO 8601可能包含秒数,见http://en.wikipedia.org/wiki/ISO_8601#次

so the code should be

所以代码应该是。

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

#10


8  

Joda-Time

Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. For Java 6 & 7, see the ThreeTen-Backport project, further adapted for Android in the ThreeTenABP project.

更新:Joda-Time项目现在处于维护模式,团队建议迁移到java。时间类。对于Java 6和7,请参阅在ThreeTenABP项目中进一步适用于Android的three - backport项目。

Using the Joda-Time library…

使用Joda-Time库……

String output = new DateTime( DateTimeZone.UTC ).toString() ;

This is thread-safe. Joda-Time creates new immutable objects rather than changing existing objects.

这是线程安全的。Joda-Time创建新的不可变对象,而不是更改现有对象。

If you truly intended to ask for a format without seconds, resolving to minutes, then use one of the many other built-in formatters in Joda-Time.

如果你真的想要一种没有秒的格式,那就把它分解成分钟,然后使用Joda-Time中的许多其他内置格式之一。

DateTime now = new DateTime( DateTimeZone.UTC ) ;
String output = ISODateTimeFormat.dateHourMinute.print( now ) ;

java.time

For Java 8 and later, Joda-Time continues to work. But the built-in java.time framework supplants Joda-Time. So migrate your code from Joda-Time to java.time as soon as is convenient.

对于Java 8和以后的版本,Joda-Time将继续工作。但是内置java。时间框架取代Joda-Time。因此,将代码从Joda-Time迁移到java。只要时间方便。

See my other Answer for a modern solution.

看看我对现代解决方案的另一个答案。


About java.time

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

java。time框架被构建到Java 8以及以后的版本中。这些类取代了麻烦的旧遗留日期时间类(如java.util)。日期,日历,& SimpleDateFormat。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

现在处于维护模式的Joda-Time项目建议向java迁移。时间类。

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

要了解更多,请参阅Oracle教程。和搜索堆栈溢出为许多例子和解释。规范是JSR 310。

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

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

Where to obtain the java.time classes?

在哪里获得java。时间类?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • 内置的。
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。
    • Java 9 adds some minor features and fixes.
    • Java 9添加了一些次要的特性和修复。
  • Java SE 8, Java SE 9, Java SE 10,以及后来的内置。部分标准Java API与绑定实现。Java 9添加了一些次要的特性和修复。
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 大部分java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Java SE 6和Java SE 7大部分Java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • java的Android bundle实现的后续版本。时间类。
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    • 对于早期的Android (<26), ThreeTenABP项目适用于three - backport(如上所述)。看到如何使用ThreeTenABP ....
  • Android后期版本的java捆绑包实现。时间类。对于早期的Android (<26), ThreeTenABP项目适用于three - backport(如上所述)。看到如何使用ThreeTenABP ....

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

三个额外的项目扩展了java。时间和额外的类。这个项目是java.time未来可能增加的一个试验场。您可以在这里找到一些有用的课程,如间隔、年周、年季等。

#11


7  

For Java version 7

对于Java version 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);

#12


5  

You could use Java's SimpleDateFormat with the following pattern yyyy-MM-dd'T'HH:mm:ssXXX for ISO 8601.

您可以使用Java的SimpleDateFormat和以下模式yyyyy - mm -dd 'HH:mm:ssXXX用于ISO 8601。

Sample Code: (lists out for all the available time zones)

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

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();
}

You could use:

您可以使用:

TimeZone.getDefault()

TimeZone.getDefault()

for the default vm timezone. More here

用于默认的vm时区。更多的在这里

You might notice the date time for few time zones that end with 'Z'. These time zones have offset of '0' from GMT.

您可能会注意到以“Z”结尾的几个时区的日期时间。这些时区由格林尼治标准时间的“0”偏移。

More info can be found here.

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

#13


4  

I do believe the easiest way is to first go to instant and then to string like:

我相信最简单的方法是先到瞬间,然后再像:

String d = new Date().toInstant().toString();

Which will result in:

这将导致:

2017-09-08T12:56:45.331Z

2017 - 09 - 08 - t12:56:45.331z

#14


2  

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());
    }
}

#15


1  

Still, joda-time does only support the extended format: "2015-12-09T00:22:42.930Z" not the basic: "20151209T002242.930Z" ...we might be better off testing a list of formats with java SimpleDateFormat.

不过,joda-time只支持扩展格式:“2015-12-09t00:22 . 930z”而不是基本格式:“20151209T002242.930Z”…我们最好使用java SimpleDateFormat测试一个格式列表。

#16


1  

I did it in Android using Calendar and SimpleDateFormat. The following method returns a Calendar with the "GMT" TimeZone (This is the universal time zone). Then you can use the Calendar class to set the hour between differents time zones, using the method setTimeZone() of the Calendar class.

我在Android中使用了Calendar和SimpleDateFormat。下面的方法返回带有“GMT”时区(这是通用时区)的日历。然后,您可以使用Calendar类使用Calendar类的方法setTimeZone()在不同的时区之间设置小时。

private static final String GMT = "GMT";
private static final String DATE_FORMAT_ISO = "yyyyMMdd'T'HHmmss";

public static Calendar isoToCalendar(final String inputDate) {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(GMT));
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_ISO, Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone(GMT));
        Date date = dateFormat.parse(inputDate);
        calendar.setTime(date);
    } catch (ParseException e) {
        Log.e("TAG",e.getMessage());
    }
    return calendar;
}

REMEMBER: The Date class doesn't know about the TimeZone existence. By this reason, if you debug one date,you always see the date for your current timezone.

记住:Date类不知道时区的存在。由于这个原因,如果调试一个日期,您总是会看到当前时区的日期。

#17


1  

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());
}

#18


0  

They should have added some kind of simple way to go from Date to Instant and also a method called toISO8601, which is what a lot of people are looking for. As a complement to other answers, from a java.util.Date to ISO 8601 format:

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

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

It is not really visible when using auto-completion but: java.time.Instant.toString():

在使用自动补全时,它不是很明显,但是:java.time. instance . tostring ():

A string representation of this instant using ISO-8601

使用ISO-8601表示这个瞬间的字符串

#19


0  

tl;dr

Some of the other Answers are correct in recommending java.time classes but go about using unnecessary lengths for your specific needs.

其他一些答案在推荐java时是正确的。时间类,但是为您的特定需求使用不必要的长度。

Instant.now()                               // Capture the current moment in UTC with a resolution as fines nanoseconds but usually in microseconds or milliseconds.
       .truncatedTo( ChronoUnit.MINUTES )   // Lop off any seconds or fractional second, to get a value in whole minutes.
       .toString()                          // Generate a String in standard ISO 8601 format where a `T` separates the year-month-day from the hour-minute-second, and the `Z` on the end for “Zulu” means UTC.

2018-01-23T12:34Z

2018 - 01 - 23 t12:34z

Instant::toString

The jav.time.Instant class represents a moment in UTC, always in UTC.

jav.time。即时类表示UTC中的一个时刻,总是在UTC中。

Instant instant = Instant.now() ;

instant.toString(): 2018-01-23T12:34:56.123456Z

instant.toString():2018 - 01 - 23 t12:34:56.123456z

The Z on the end of your example string 2010-10-12T08:50Z is pronounced “Zulu” and means UTC.

示例字符串2010-10-12T08:50Z末尾的Z发音为“Zulu”,表示UTC。

Your desired format happens to comply with the ISO 8601 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern. Just call Instant::toString as seen above.

您想要的格式恰好符合ISO 8601标准。java。在解析/生成字符串时,时间类默认使用这些标准格式。因此不需要指定格式模式。只需调用Instant::toString,如上所示。

If you specifically want whole minutes without second or fractional second, then truncate. Specify a unit of time via ChronoUnit class.

如果你特别想要一分钟不超过一秒或几秒,那就截断。通过ChronoUnit类指定时间单位。

Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES ) ;
String output = instant.toString();  // Generate a `String` object in standard ISO 8601 format.

About java.time

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

java。time框架被构建到Java 8以及以后的版本中。这些类取代了麻烦的旧遗留日期时间类(如java.util)。日期,日历,& SimpleDateFormat。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

现在处于维护模式的Joda-Time项目建议向java迁移。时间类。

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

要了解更多,请参阅Oracle教程。和搜索堆栈溢出为许多例子和解释。规范是JSR 310。

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

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

Where to obtain the java.time classes?

在哪里获得java。时间类?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • 内置的。
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。
    • Java 9 adds some minor features and fixes.
    • Java 9添加了一些次要的特性和修复。
  • Java SE 8, Java SE 9, Java SE 10,以及后来的内置。部分标准Java API与绑定实现。Java 9添加了一些次要的特性和修复。
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 大部分java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Java SE 6和Java SE 7大部分Java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • java的Android bundle实现的后续版本。时间类。
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    • 对于早期的Android (<26), ThreeTenABP项目适用于three - backport(如上所述)。看到如何使用ThreeTenABP ....
  • Android后期版本的java捆绑包实现。时间类。对于早期的Android (<26), ThreeTenABP项目适用于three - backport(如上所述)。看到如何使用ThreeTenABP ....

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

三个额外的项目扩展了java。时间和额外的类。这个项目是java.time未来可能增加的一个试验场。您可以在这里找到一些有用的课程,如间隔、年周、年季等。

#20


-1  

DateTimeFormatter.ISO_DATE_TIME
        .withZone(ZoneOffset.UTC)
        .format(yourDateObject.toInstant())

#21


-3  

Try This,

试试这个,

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ");
        String date=sdf.format (new Date() );

Its For ISO 8601 format

它适用于ISO 8601格式

#1


211  

Use SimpleDateFormat to format any Date object you want:

使用SimpleDateFormat设置您想要的任何日期对象:

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());

Using a new Date() as shown above will format the current time.

使用上面所示的新日期()将格式化当前时间。

#2


201  

For systems where the default Time Zone is not UTC:

对于默认时区不是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());

The SimpleDateFormat instance may be declared as a global constant if needed frequently, but beware that this class is not thread-safe. It must be synchronized if accessed concurrently by multiple threads.

如果经常需要,SimpleDateFormat实例可能被声明为全局常量,但是要注意这个类不是线程安全的。如果由多个线程同时访问,则必须对其进行同步。

EDIT: I would prefer Joda Time if doing many different Times/Date manipulations...
EDIT2: corrected: setTimeZone does not accept a String (corrected by Paul)

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

#3


109  

Java 8:

Java 8:

thisMoment = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX")
                              .withZone(ZoneOffset.UTC)
                              .format(Instant.now());

Pre Java 8:

以前的Java 8:

thisMoment = String.format("%tFT%<tRZ",
                           Calendar.getInstance(TimeZone.getTimeZone("Z")));

From the docs:

从文档:

'R'    Time formatted for the 24-hour clock as "%tH:%tM"
'F'    ISO 8601 complete date formatted as "%tY-%tm-%td".

24小时时钟的'R'时间格式为' %tH:%tM ' ' ' 'F' ISO 8601完整日期格式为' %tY-% tM -%td '。

#4


89  

Java 8 Native

java.time makes it simple since Java 8. And thread safe.

java。自Java 8以来,时间使它变得简单。和线程安全的。

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

Result: 2015-04-14T11:07:36.639Z

结果:2015 - 04 - 14 - t11:07:36.639z

You may be tempted to use lighter Temporal such as Instant or LocalDateTime, but they lacks formatter support or time zone data. Only ZonedDateTime works out of the box.

您可能倾向于使用较轻的时态,例如Instant或LocalDateTime,但它们缺乏格式化程序支持或时区数据。只有ZonedDateTime可以在这个框中工作。

By tuning or chaining the options / operations of ZonedDateTime and DateTimeFormatter, you can easily control the timezone and precision, to a certain degree:

通过调优或链接ZonedDateTime和DateTimeFormatter的选项/操作,您可以轻松地控制时区和精度,在一定程度上:

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

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

结果:2015 - 04 - 14 - t11:07:00 + 01:00(欧洲/巴黎)

Refined requirements, such as removing the seconds part, must still be served by custom formats or custom post process.

改进的需求,例如删除秒部分,仍然必须使用自定义格式或自定义post过程。

.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

For Java 6 & 7, you may consider back-ports of java.time such as ThreeTen-Backport, which also has an Android port. Both are lighter than Joda, and has learned from Joda's experience - esp. considering that java.time is designed by Joda's author.

对于Java 6和7,您可以考虑Java的后端端口。时间,比如3 - backport,它也有一个Android端口。两者都比Joda轻,并且从Joda的经验中学到了很多——尤其是考虑到java。时间是由Joda的作者设计的。

#5


25  

use JodaTime

使用JodaTime

The ISO 8601 calendar system is the default implementation within Joda-Time

ISO 8601日历系统是Joda-Time内的默认实现

Here is the doc for JodaTime Formatter

这是JodaTime Formatter的博士

Edit:

编辑:

If you don't want to add or if you don't see value of adding above library you could just use in built SimpleDateFormat class to format the Date to required ISO format

如果您不想添加,或者您没有看到添加上述库的价值,您可以使用build SimpleDateFormat类将日期格式化为所需的ISO格式

as suggested by @Joachim Sauer

正如@Joachim Sauer所建议的那样

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
String nowAsString = df.format(new Date());

#6


20  

DateFormatUtils from Apache commons-lang3 have useful constants, for example: DateFormatUtils.ISO_DATETIME_FORMAT

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

#7


19  

As of Java 8 you can simply do:

从Java 8开始,你可以简单地做到:

Instant.now().toString();

From the java.time.Instant docs:

从java.time。即时文档:

now

public static Instant now()

公共静态即时现在()

Obtains the current instant from the system clock.

从系统时钟获取当前瞬间。

This will query the system UTC clock to obtain the current instant.

这将查询系统UTC时钟以获得当前的即时。

 

 

toString

public String toString()

公共字符串toString()

A string representation of this instant using ISO-8601 representation.

使用ISO-8601表示的字符串表示。

The format used is the same as DateTimeFormatter.ISO_INSTANT.

所使用的格式与datetimeformat . iso_instant相同。

#8


18  

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。

#9


13  

ISO 8601 may contains seconds see http://en.wikipedia.org/wiki/ISO_8601#Times

ISO 8601可能包含秒数,见http://en.wikipedia.org/wiki/ISO_8601#次

so the code should be

所以代码应该是。

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

#10


8  

Joda-Time

Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. For Java 6 & 7, see the ThreeTen-Backport project, further adapted for Android in the ThreeTenABP project.

更新:Joda-Time项目现在处于维护模式,团队建议迁移到java。时间类。对于Java 6和7,请参阅在ThreeTenABP项目中进一步适用于Android的three - backport项目。

Using the Joda-Time library…

使用Joda-Time库……

String output = new DateTime( DateTimeZone.UTC ).toString() ;

This is thread-safe. Joda-Time creates new immutable objects rather than changing existing objects.

这是线程安全的。Joda-Time创建新的不可变对象,而不是更改现有对象。

If you truly intended to ask for a format without seconds, resolving to minutes, then use one of the many other built-in formatters in Joda-Time.

如果你真的想要一种没有秒的格式,那就把它分解成分钟,然后使用Joda-Time中的许多其他内置格式之一。

DateTime now = new DateTime( DateTimeZone.UTC ) ;
String output = ISODateTimeFormat.dateHourMinute.print( now ) ;

java.time

For Java 8 and later, Joda-Time continues to work. But the built-in java.time framework supplants Joda-Time. So migrate your code from Joda-Time to java.time as soon as is convenient.

对于Java 8和以后的版本,Joda-Time将继续工作。但是内置java。时间框架取代Joda-Time。因此,将代码从Joda-Time迁移到java。只要时间方便。

See my other Answer for a modern solution.

看看我对现代解决方案的另一个答案。


About java.time

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

java。time框架被构建到Java 8以及以后的版本中。这些类取代了麻烦的旧遗留日期时间类(如java.util)。日期,日历,& SimpleDateFormat。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

现在处于维护模式的Joda-Time项目建议向java迁移。时间类。

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

要了解更多,请参阅Oracle教程。和搜索堆栈溢出为许多例子和解释。规范是JSR 310。

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

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

Where to obtain the java.time classes?

在哪里获得java。时间类?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • 内置的。
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。
    • Java 9 adds some minor features and fixes.
    • Java 9添加了一些次要的特性和修复。
  • Java SE 8, Java SE 9, Java SE 10,以及后来的内置。部分标准Java API与绑定实现。Java 9添加了一些次要的特性和修复。
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 大部分java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Java SE 6和Java SE 7大部分Java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • java的Android bundle实现的后续版本。时间类。
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    • 对于早期的Android (<26), ThreeTenABP项目适用于three - backport(如上所述)。看到如何使用ThreeTenABP ....
  • Android后期版本的java捆绑包实现。时间类。对于早期的Android (<26), ThreeTenABP项目适用于three - backport(如上所述)。看到如何使用ThreeTenABP ....

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

三个额外的项目扩展了java。时间和额外的类。这个项目是java.time未来可能增加的一个试验场。您可以在这里找到一些有用的课程,如间隔、年周、年季等。

#11


7  

For Java version 7

对于Java version 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);

#12


5  

You could use Java's SimpleDateFormat with the following pattern yyyy-MM-dd'T'HH:mm:ssXXX for ISO 8601.

您可以使用Java的SimpleDateFormat和以下模式yyyyy - mm -dd 'HH:mm:ssXXX用于ISO 8601。

Sample Code: (lists out for all the available time zones)

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

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();
}

You could use:

您可以使用:

TimeZone.getDefault()

TimeZone.getDefault()

for the default vm timezone. More here

用于默认的vm时区。更多的在这里

You might notice the date time for few time zones that end with 'Z'. These time zones have offset of '0' from GMT.

您可能会注意到以“Z”结尾的几个时区的日期时间。这些时区由格林尼治标准时间的“0”偏移。

More info can be found here.

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

#13


4  

I do believe the easiest way is to first go to instant and then to string like:

我相信最简单的方法是先到瞬间,然后再像:

String d = new Date().toInstant().toString();

Which will result in:

这将导致:

2017-09-08T12:56:45.331Z

2017 - 09 - 08 - t12:56:45.331z

#14


2  

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());
    }
}

#15


1  

Still, joda-time does only support the extended format: "2015-12-09T00:22:42.930Z" not the basic: "20151209T002242.930Z" ...we might be better off testing a list of formats with java SimpleDateFormat.

不过,joda-time只支持扩展格式:“2015-12-09t00:22 . 930z”而不是基本格式:“20151209T002242.930Z”…我们最好使用java SimpleDateFormat测试一个格式列表。

#16


1  

I did it in Android using Calendar and SimpleDateFormat. The following method returns a Calendar with the "GMT" TimeZone (This is the universal time zone). Then you can use the Calendar class to set the hour between differents time zones, using the method setTimeZone() of the Calendar class.

我在Android中使用了Calendar和SimpleDateFormat。下面的方法返回带有“GMT”时区(这是通用时区)的日历。然后,您可以使用Calendar类使用Calendar类的方法setTimeZone()在不同的时区之间设置小时。

private static final String GMT = "GMT";
private static final String DATE_FORMAT_ISO = "yyyyMMdd'T'HHmmss";

public static Calendar isoToCalendar(final String inputDate) {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(GMT));
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_ISO, Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone(GMT));
        Date date = dateFormat.parse(inputDate);
        calendar.setTime(date);
    } catch (ParseException e) {
        Log.e("TAG",e.getMessage());
    }
    return calendar;
}

REMEMBER: The Date class doesn't know about the TimeZone existence. By this reason, if you debug one date,you always see the date for your current timezone.

记住:Date类不知道时区的存在。由于这个原因,如果调试一个日期,您总是会看到当前时区的日期。

#17


1  

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());
}

#18


0  

They should have added some kind of simple way to go from Date to Instant and also a method called toISO8601, which is what a lot of people are looking for. As a complement to other answers, from a java.util.Date to ISO 8601 format:

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

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

It is not really visible when using auto-completion but: java.time.Instant.toString():

在使用自动补全时,它不是很明显,但是:java.time. instance . tostring ():

A string representation of this instant using ISO-8601

使用ISO-8601表示这个瞬间的字符串

#19


0  

tl;dr

Some of the other Answers are correct in recommending java.time classes but go about using unnecessary lengths for your specific needs.

其他一些答案在推荐java时是正确的。时间类,但是为您的特定需求使用不必要的长度。

Instant.now()                               // Capture the current moment in UTC with a resolution as fines nanoseconds but usually in microseconds or milliseconds.
       .truncatedTo( ChronoUnit.MINUTES )   // Lop off any seconds or fractional second, to get a value in whole minutes.
       .toString()                          // Generate a String in standard ISO 8601 format where a `T` separates the year-month-day from the hour-minute-second, and the `Z` on the end for “Zulu” means UTC.

2018-01-23T12:34Z

2018 - 01 - 23 t12:34z

Instant::toString

The jav.time.Instant class represents a moment in UTC, always in UTC.

jav.time。即时类表示UTC中的一个时刻,总是在UTC中。

Instant instant = Instant.now() ;

instant.toString(): 2018-01-23T12:34:56.123456Z

instant.toString():2018 - 01 - 23 t12:34:56.123456z

The Z on the end of your example string 2010-10-12T08:50Z is pronounced “Zulu” and means UTC.

示例字符串2010-10-12T08:50Z末尾的Z发音为“Zulu”,表示UTC。

Your desired format happens to comply with the ISO 8601 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern. Just call Instant::toString as seen above.

您想要的格式恰好符合ISO 8601标准。java。在解析/生成字符串时,时间类默认使用这些标准格式。因此不需要指定格式模式。只需调用Instant::toString,如上所示。

If you specifically want whole minutes without second or fractional second, then truncate. Specify a unit of time via ChronoUnit class.

如果你特别想要一分钟不超过一秒或几秒,那就截断。通过ChronoUnit类指定时间单位。

Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES ) ;
String output = instant.toString();  // Generate a `String` object in standard ISO 8601 format.

About java.time

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

java。time框架被构建到Java 8以及以后的版本中。这些类取代了麻烦的旧遗留日期时间类(如java.util)。日期,日历,& SimpleDateFormat。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

现在处于维护模式的Joda-Time项目建议向java迁移。时间类。

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

要了解更多,请参阅Oracle教程。和搜索堆栈溢出为许多例子和解释。规范是JSR 310。

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

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

Where to obtain the java.time classes?

在哪里获得java。时间类?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • 内置的。
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。
    • Java 9 adds some minor features and fixes.
    • Java 9添加了一些次要的特性和修复。
  • Java SE 8, Java SE 9, Java SE 10,以及后来的内置。部分标准Java API与绑定实现。Java 9添加了一些次要的特性和修复。
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 大部分java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Java SE 6和Java SE 7大部分Java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • java的Android bundle实现的后续版本。时间类。
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    • 对于早期的Android (<26), ThreeTenABP项目适用于three - backport(如上所述)。看到如何使用ThreeTenABP ....
  • Android后期版本的java捆绑包实现。时间类。对于早期的Android (<26), ThreeTenABP项目适用于three - backport(如上所述)。看到如何使用ThreeTenABP ....

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

三个额外的项目扩展了java。时间和额外的类。这个项目是java.time未来可能增加的一个试验场。您可以在这里找到一些有用的课程,如间隔、年周、年季等。

#20


-1  

DateTimeFormatter.ISO_DATE_TIME
        .withZone(ZoneOffset.UTC)
        .format(yourDateObject.toInstant())

#21


-3  

Try This,

试试这个,

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ");
        String date=sdf.format (new Date() );

Its For ISO 8601 format

它适用于ISO 8601格式