Java Date Format ISO formatISO8601(Date date, TimeZone timeZone)

Here you can find the source of formatISO8601(Date date, TimeZone timeZone)

Description

Formats a DateTime to a ISO8601 string with a second fraction part of up to 3 digits.

License

Open Source License

Declaration

public static String formatISO8601(Date date, TimeZone timeZone) 

Method Source Code

//package com.java2s;
/**/*from   w w  w. ja v  a  2s . c o m*/
 * Copyright (c) 2014-2015 by Wen Yu.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Any modifications to this file must keep this entire header intact.
 */

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {
    /**
     * Formats a DateTime to a ISO8601 string with a second fraction part of up to 3 digits.
     */
    public static String formatISO8601(Date date, TimeZone timeZone) {

        SimpleDateFormat df = null;

        if (timeZone != null) {
            df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSSZ");
            df.setTimeZone(timeZone);

            String result = df.format(date);

            if (result.endsWith("0000"))
                return result.replaceAll("[+-]0000$", "Z");

            return result.replaceAll("(\\d{2})(\\d{2})$", "$1:$2");
        }

        df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

        return df.format(date);
    }

    public static String format(Date date, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);

        return df.format(date);
    }

    public static String format(Date date) {
        return format(date, "yyyy-MM-dd'T'HH:mm:ss.SSS");
    }
}

Related

  1. formatISO8601(Date date)
  2. formatIso8601(Date date)
  3. formatIso8601(Date date)
  4. formatISO8601(Date date)
  5. formatIso8601(Date date)
  6. formatISO8601(final Date date)
  7. formatISO8601(final Date date)
  8. formatISO8601Date(Date d)
  9. formatISO8601Date(Date date)