How to convert ISO 8601 date (string) to Date?

[亡魂溺海] 提交于 2019-12-01 10:52:44

Use java.text.DateFormat - or more likely, SimpleDateFormat.

Alternatively, go for Joda Time with its infinitely better API. Be careful with the Java built-in APIs - DateFormats aren't thread-safe. (They are in Joda Time, which uses immutable types almost everywhere.)

An (untested - should be fine except for possibly the timezone bit) example for the Joda Time API:

DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd'T'HH:mm:ssZ");
DateTime dt = fmt.parse("2008-11-10T05:51:33Z");

tl;dr

Instant.parse( "2008-11-10T05:51:33Z" ) 

Using java.time

The modern approach uses the java.time classes. Avoid the troublesome older date-time classes such as Date and Calendar as they are now supplanted by java.time classes.

ISO 8601

Your input string complies with the ISO 8601 standard for formatting strings representing date-time values. The java.time classes use the standard formats by default when parsing/generating strings, so no need to specify a formatting pattern.

The Z on the end is short for Zulu and means UTC.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.parse( "2008-11-10T05:51:33Z" ) ;

java.util.Date

Best to avoid the old legacy class java.util.Date. But if you must, you can convert to/from java.time by calling new methods added to the old classes. Here we use Date.from.

java.util.Date d = java.util.Date.from( instant ) ;

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.

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

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is 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.

Where to obtain the java.time classes?

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.

DateTime dateToGetFromString;

dateToGetFromString = DateTime.Parse(stringContainingDate);

You can also use the TryParse function of DateTime class, look in the documentation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!