Search code examples
javadateiso8601

Formatting ISO 8601 date with a colon seperator


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 ?


Solution

  • You can always use a StringBuilder:

    new StringBuilder(
          new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
          .format(date))
        .insert(22,':')
        .toString();