Java Date XML Format formatXml(Date date)

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

Description

Convert date to XML format

License

Open Source License

Parameter

Parameter Description
date a parameter

Declaration

public static String formatXml(Date date) 

Method Source Code


//package com.java2s;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.TimeZone;

public class Main {
    public static final String _DATE_MAX = "9999-12-31 23:59:59";

    /**//  w w w . j  a va 2  s .  c o m
     * Convert date to XML format
     * @param date
     * @return 
     */
    public static String formatXml(Date date) {
        return formatXml(date, null);
    }

    /**
     * Convert date with time zone to XML format
     * @param date
     * @param tz
     * @return 
     */
    public static String formatXml(Date date, TimeZone tz) {
        if (tz == null)
            tz = TimeZone.getDefault();
        if (date.after(getMax()))
            date = getMax();
        SimpleDateFormat outputXmlFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        outputXmlFmt.setTimeZone(tz);
        String result = outputXmlFmt.format(date) + " " + getGMTString(date, tz);
        return result;
    }

    public static Date getMax() {
        return toDate(_DATE_MAX);
    }

    private static String getGMTString(Date date, TimeZone tz) {
        DecimalFormat fmt = new DecimalFormat("'GMT'+00':00';'GMT'-00':00'");
        int off = tz.getRawOffset();
        if (tz.inDaylightTime(date))
            off += 3600000;
        off = off / 3600000;
        return fmt.format(off);
    }

    /**
     * This function is use to convert string date format to data format
     * @param dateStr
     * @return 
     */
    public static Date toDate(String dateStr) {
        return toDate(dateStr, null);
    }

    /**
     * Convert string date format with time zone
     * @param dateStr
     * @param tz
     * @return 
     */
    public static Date toDate(String dateStr, TimeZone tz) {
        if (tz == null)
            tz = TimeZone.getDefault();
        if (dateStr == null)
            return null;

        SimpleDateFormat fmt = null;
        if (dateStr.length() == 19) {
            fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            fmt.setTimeZone(tz);
        } else {
            fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        }
        try {
            return fmt.parse(dateStr);
        } catch (ParseException e) {

            return null;
        }
    }
}

Related

  1. formatDateToXML(Date dateTime)
  2. formatToXMLDate(Date date)
  3. formatXMLDate(Date date, String pattern)
  4. getTime(String xmlDateTime)
  5. getXmlTime(Date date)
  6. parse(String xmlDateTime)