Java Date Format ISO formatISO8601Date(Date d)

Here you can find the source of formatISO8601Date(Date d)

Description

Convert a Date to String in the ISO 8601 standard format.

License

BSD License

Parameter

Parameter Description
d the input Date

Return

String containing formatted date.

Declaration

public static synchronized String formatISO8601Date(Date d) 

Method Source Code

//package com.java2s;
/**/*from w ww  .  j a va2s .c  o  m*/
 * The contents of this file are subject to the license and copyright
 * detailed in the LICENSE and NOTICE files at the root of the source
 * tree and available online at
 *
 * http://www.dspace.org/license/
 */

import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;

public class Main {
    private static SimpleDateFormat outFmtSecond = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ");
    private static SimpleDateFormat outFmtMillisec = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZ");
    private static Calendar outCal = GregorianCalendar.getInstance();

    /**
     * Convert a Date to String in the ISO 8601 standard format.
     * The RFC822 timezone is almost right, still need to insert ":".
     * This method is synchronized because it depends on a non-reentrant
     * static DateFormat (more efficient than creating a new one each call).
     *
     * @param d the input Date
     * @return String containing formatted date.
     */
    public static synchronized String formatISO8601Date(Date d) {
        String result;
        outCal.setTime(d);
        if (outCal.get(Calendar.MILLISECOND) == 0) {
            result = outFmtSecond.format(d);
        } else {
            result = outFmtMillisec.format(d);
        }
        int rl = result.length();
        return result.substring(0, rl - 2) + ":" + result.substring(rl - 2);
    }
}

Related

  1. formatISO8601(Date date)
  2. formatIso8601(Date date)
  3. formatISO8601(Date date, TimeZone timeZone)
  4. formatISO8601(final Date date)
  5. formatISO8601(final Date date)
  6. formatISO8601Date(Date date)
  7. formatISO8601Date(Date date)
  8. formatIso8601Date(Date date)
  9. formatISO8601Date(Date date)