Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting ISO 8601 date with a colon seperator

Tags:

java

date

iso8601

I am trying to convert the date in milliseconds to the following ISO 8601 format:

enter image description here

But I am getting the following using SimpleDateFormat:

    /**
     * It converts the time from long to the ISO format
     * 
     * @param timestampMillis
     * @return isoDate
     */
    public String convertTimeMillisToISO8601(String timestampMillis)
    {
        long timeInLong= Long.parseLong(timestampMillis);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        String isoDate = df.format(new java.util.Date(timeInLong));
        return isoDate;
    }

OUTPUT:

"ts":"2015-06-18T09:56:21+0000"

I know I can use substring to append the extra colon but Is there any better way to do so ?

like image 216
My God Avatar asked Dec 25 '22 20:12

My God


1 Answers

For Java 7 and higher, you might use XXX (ISO 8601 time zone) in the date format String. According to the documentation, the result of X can be:

X    => -08
XX   => -0800
XXX  => -08:00

but for all of those, it might as well return Z!

For Java 6 and earlier, there is no X (J6 doc), and since the result of X may or may not do what you want, I strongly recommend you just insert that colon yourself.

like image 73
Siguza Avatar answered Dec 27 '22 10:12

Siguza