Java Date Format ISO formatISO8601(Date date)

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

Description

format ISO

License

Open Source License

Declaration

public static String formatISO8601(Date date) 

Method Source Code

//package com.java2s;
/**//from  www  .  j a  v  a  2s  .co  m
 * Copyright (c) 2014-2016 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 {
    public static String formatISO8601(Date date) {
        return format(date, "yyyy-MM-dd'T'HH:mm:ss.SSS");
    }

    /**
      * 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);
    }
}

Related

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