简体   繁体   中英

convert string timestamp to ISO 8601 compliant string

I have a timestamp and offset in string format as shown below in two different variables:

01/14/2016 07:37:36PM
-08:00

I want to convert above timestamp into ISO 8601 compliant String, with milliseconds and timezone so it should look like this after conversion:

2016-01-14T19:37:36-08:00

How can I do that? I am using jodatime library.

The newer java.time classes work so well with ISO 8601 strings.

    String dateTimeString = "01/14/2016 07:37:36PM"; 
    String offsetString = "-08:00";

    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString,
            DateTimeFormatter.ofPattern("MM/dd/uuuu hh:mm:ssa"));
    ZoneOffset offset = ZoneOffset.of(offsetString);
    String formattedTimestamp = dateTime.atOffset(offset).toString();
    System.out.println(formattedTimestamp);

This prints

2016-01-14T19:37:36-08:00

Stay away from outdated classes like SimpleDateFormat .

What is offsetString is not present? I understand that in this case you want an offset of Z for UTC. For example like this:

    ZoneOffset offset;
    if (offsetString == null) {
        offset = ZoneOffset.UTC;
    } else {
        offset = ZoneOffset.of(offsetString);
    }
    String formattedTimestamp = dateTime.atOffset(offset).toString();

With a null offsetString we now get

2016-01-14T19:37:36Z

The classes in java.time (of which I'm using but a few) are described in JSR-310 and come built-in with Java 8. What if you would like to use them with Java 6 or 7? You get the ThreeTen Backport (link below). It gives you the majority of the classes for Java 6 and 7. I'm not perfectly happy to tell you you need an external library, but in this case it's only until you move to Java 8. I hope you will soon.

I am sure it can be done with JodaTime too, but I haven't got experience with it, so cannot give you the details there. What I do know, I have read the the folks behind JodaTime now recommend you move over to java.time instead. So I am asking you to swap one external library for a newer (and supposedly better) one. In itself I'm not unhappy with that. Only if you already have a codebase that uses JodaTime, it's not really trivial.

Link: ThreeTen Backport

You can find more examples in section Examples at :- http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String string2 = "2001-07-04T12:08:56.235-07:00";
Date result2 = df2.parse(string2);

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