Java Date Convert dateToXmlDateTime(final Date date)

Here you can find the source of dateToXmlDateTime(final Date date)

Description

Calculates a valid xsd:dateTime value from a given date.

License

Open Source License

Parameter

Parameter Description
date a parameter

Declaration

public static String dateToXmlDateTime(final Date date) 

Method Source Code


//package com.java2s;
/*/*w ww.  j  a v a2  s  .co  m*/
 * Copyright 2007 Joachim Sauer
 * Copyright 2002-2006 Chriss Veness (vincenty formula in distance())
 * 
 * This file is part of bbTracker.
 * 
 * bbTracker is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * bbTracker is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Main {
    public static final char MINUTE = '\'';
    public static final char SECOND = '"';

    /**
     * Calculates a valid xsd:dateTime value from a given date.
     * 
     * The XML Schema standard defines a dateTime roughly as
     * "YYYY-MM-DDThh:mm:ss(.s+)? (zzzzzz)?"
     * 
     * @param date
     * @return
     */
    public static String dateToXmlDateTime(final Date date) {
        final TimeZone utc = TimeZone.getTimeZone("GMT");
        final Calendar c = Calendar.getInstance(utc);
        c.setTime(date);
        final StringBuffer result = new StringBuffer(24);
        result.append(c.get(Calendar.YEAR)).append('-');
        appendTwoDigits(result, c.get(Calendar.MONTH) + 1, '0').append('-');
        appendTwoDigits(result, c.get(Calendar.DATE), '0').append('T');
        appendTwoDigits(result, c.get(Calendar.HOUR_OF_DAY), '0').append(':');
        appendTwoDigits(result, c.get(Calendar.MINUTE), '0').append(':');
        appendTwoDigits(result, c.get(Calendar.SECOND), '0').append('.');
        final int millisecond = c.get(Calendar.MILLISECOND);
        if (millisecond < 100) {
            result.append('0');
        }
        appendTwoDigits(result, millisecond, '0').append('Z');

        return result.toString();
    }

    private static StringBuffer appendTwoDigits(final StringBuffer buf, final int value, final char c) {
        if (value < 10) {
            buf.append(c);
        }
        buf.append(value);
        return buf;
    }
}

Related

  1. dateToString(Date date)
  2. dateToString(final Date date)
  3. dateToUnixTimestamp(Date date)
  4. dateToUTC(Date d)
  5. dateToXdsDateString(Date date, int format)