简体   繁体   中英

Having issues formatting a specific Date/Time format

I'm having issues formatting the following date/time:

2013-01-10T17:04:24.3787635-02:00

Now, I understand 2013-01-10 is the date (obviously).

17:04:24.3787635 probably time, though I have no idea what the numbers after the dot mean.

-02:00 I assume it's the time zone (GMT).

How can I parse this in java? (maybe using JodaTime).

Try using this pattern:

"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"

Which can parse date in this format:

2001-07-04T12:08:56.235-07:00

Although, 3787635 in your source string is troublesome. It doesn't look like milliseconds.

Take a look at java.text.SimpleDateFormat for additional details on patterns.

You can also try DatatypeConverter.parseDateTime which returns a java.util.Calendar object.

DatatypeConverter.parseDateTime("2013-01-10T17:04:24.3787635-02:00").getTime()

The above statement executes without any errors.

You could use JodaTime to parse this date:

String time = "2013-01-10T17:04:24.3787635-02:00";
DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ");
DateTime dateTime = df.parseDateTime(time);

The numbers after the dot ( . ) are the fractions of seconds denoted by S in JodaTime's DateTimeFormat . Z represents the timezone pattern.

The format of your time string is the ISO8601 format. The JodaTime class ISODateTimeFormat will support that format directly. You will lose any accuracy beyond millisecond, however.

String time = "2013-01-10T17:04:24.3787635-02:00";
DateTime dateTime = ISODateTimeFormat.dateTime().parseDateTime(time);

This format can be parsed correctly only with javax.xml.XMLGregorianCalendar. You cannot use SimpleDateFormat because it accepts SSS as number of milliseconds, not as fractional part of a second.

    String s = "2013-01-10T17:04:24.3787635-02:00";
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    Date date = dtf.newXMLGregorianCalendar(s).toGregorianCalendar().getTime();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM