Parse W3C Date format : Date Format « Data Type « Java

Parse W3C Date format


/* infoScoop OpenSource
 * Copyright (C) 2010 Beacon IT Inc.
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * as published by the Free Software Foundation.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program.  If not, see
 * <>.

//package org.infoscoop.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

 * @author Atsuhiko Kimura
public class DateUtility {

  private static final String W3CDTF_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";

  private static SimpleDateFormat FULL_DATE = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
  private static SimpleDateFormat DEFAULT_DATE = new SimpleDateFormat( "EEE, d MMM yyyy HH:mm:ss Z" );
  private static SimpleDateFormat formatGMT = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);

  private static SimpleDateFormat format1 = new SimpleDateFormat(

  private static SimpleDateFormat format2 = new SimpleDateFormat(
      "yyyy-MM-dd HH:mm:ssZ");

  private static SimpleDateFormat format3 = new SimpleDateFormat(
      "yyyy-MM-dd HH:mm:ss'Z'");
  // Fri Sep 14 11:05:53 JST 2007
  private static SimpleDateFormat imap4Date = new SimpleDateFormat(
      "EEE MMM d HH:mm:ss 'JST' yyyy", Locale.ENGLISH);
  public static DateFormat newW3CDFWithoutSecond(){
    return (DateFormat) format1.clone();

  public static DateFormat newW3CDFWithoutT(){
    return (DateFormat) format2.clone();
  public static DateFormat newImap4DateFormat(){
    return (DateFormat) imap4Date.clone();
  public static DateFormat newGMTDateFormat(){
    return (DateFormat) formatGMT.clone();
   * We convert a date of java.util.Date type into a W3CDTF form.
   * @param date
   * @return
  public static String getW3CDTFDate(Date date) {
    String str = new SimpleDateFormat( W3CDTF_FORMAT ).format(date);
    str = str.substring(0, str.length() - 2) + ":"
        + str.substring(str.length() - 2);
    return str;

  public static Date parseW3CDTFDate(String dateString){
    Matcher m = null;
    if ((m = W3CDTF_FORMAT1.matcher(dateString)).matches()) {
      TimeZone tz;
      if( "Z".equals( {
        tz = TimeZone.getTimeZone("GMT+00:00");
      } else {
        tz = TimeZone.getTimeZone("GMT" +;
      Calendar c = Calendar.getInstance(tz);
      int year = Integer.parseInt(;
      int month = Integer.parseInt( - 1;
      int date = Integer.parseInt(;
      int hour = Integer.parseInt(;
      int minute = Integer.parseInt(;
      int second = Integer.parseInt(;
      c.set(year, month, date, hour, minute, second);
      c.set(Calendar.MILLISECOND, 0);
      return c.getTime();
    if ((m = W3CDTF_FORMAT2.matcher(dateString)).matches()) {
      TimeZone tz;
      if( "Z".equals( {
        tz = TimeZone.getTimeZone("GMT+00:00");
      } else {
        tz = TimeZone.getTimeZone("GMT" +;
      Calendar c = Calendar.getInstance(tz);
      int year = Integer.parseInt(;
      int month = Integer.parseInt( - 1;
      int date = Integer.parseInt(;
      int hour = Integer.parseInt(;
      int minute = Integer.parseInt(;
      c.set(year, month, date, hour, minute, 0);
      c.set(Calendar.MILLISECOND, 0);
      return c.getTime();
    if ((m = W3CDTF_FORMAT3.matcher(dateString)).matches()) {
      Calendar c = Calendar.getInstance();
      int year = Integer.parseInt(;
      int month = Integer.parseInt( - 1;
      int date = Integer.parseInt(;
      c.set(year, month, date, 0, 0, 0);
      c.set(Calendar.MILLISECOND, 0);
      return c.getTime();
    if ((m = W3CDTF_FORMAT4.matcher(dateString)).matches()) {
      Calendar c = Calendar.getInstance();
      int year = Integer.parseInt(;
      int month = Integer.parseInt( - 1;
      c.set(year, month, 1, 0, 0, 0);
      c.set(Calendar.MILLISECOND, 0);
      return c.getTime();
    if ((m = W3CDTF_FORMAT5.matcher(dateString)).matches()) {
      Calendar c = Calendar.getInstance();
      int year = Integer.parseInt(;
      c.set(year, 0, 1, 0, 0, 0);
      c.set(Calendar.MILLISECOND, 0);
      return c.getTime();
    return null;

   * We convert the date of the W3CDTF form into java.util.Date type.
   * @param W3CDTFDate
   * @return
  public static Date getDateFromW3CDTF(String w3cDTFDate) {
    if (w3cDTFDate == null || w3cDTFDate.length() == 0)
      return null;

    try {
      int year = Integer.parseInt(w3cDTFDate.substring(0, 4));
      int month = Integer.parseInt(w3cDTFDate.substring(5, 7));
      int day = Integer.parseInt(w3cDTFDate.substring(8, 10));
      int hour = Integer.parseInt(w3cDTFDate.substring(11, 13));
      int minute = Integer.parseInt(w3cDTFDate.substring(14, 16));
      int second = Integer.parseInt(w3cDTFDate.substring(17, 19));
      String zone = "GMT" + w3cDTFDate.substring(19);
      Calendar cal = Calendar.getInstance();
      cal.set(year, month - 1, day, hour, minute, second);
      cal.set(Calendar.MILLISECOND, 0);
      return cal.getTime();
    } catch (Exception e) {
      System.out.println(w3cDTFDate + " is invalid date string.");

    return null;

  private static final String YMD= "([0-9]{4})-([0-9]{2})-([0-9]{2})";
  private static final String ZONE = "(Z|(?:[\\\\+\\\\-][0-9]{2}:[0-9]{2}))";
  private static final Pattern W3CDTF_FORMAT1 = Pattern.compile( YMD+"[T ]([0-9]{2}):([0-9]{2}):([0-9]{2})"+ZONE );
  private static final Pattern W3CDTF_FORMAT2 = Pattern.compile( YMD+"[T ]([0-9]{2}):([0-9]{2})"+ZONE );
  private static final Pattern W3CDTF_FORMAT3 = Pattern.compile( YMD );
  private static final Pattern W3CDTF_FORMAT4 = Pattern.compile("([0-9]{4})-([0-9]{2})");
  private static final Pattern W3CDTF_FORMAT5 = Pattern.compile("([0-9]{4})");
  public static boolean isToday(Date date) {
        GregorianCalendar now = new GregorianCalendar();
        GregorianCalendar then = new GregorianCalendar();
        return isSameDay(now, then);

  public static boolean isSameDay(Calendar calA, Calendar calB) {
          return (calA.get(Calendar.YEAR) == calB.get(Calendar.YEAR) &&
                          calA.get(Calendar.DAY_OF_YEAR) == calB.get(Calendar.DAY_OF_YEAR));


Related examples in the same category

1.Date Era changeDate Era change
2.Date Format
3.The Time and Date Format Suffixes
4.Display standard 12-hour time format
5.Display complete time and date information
6.Display just hour and minute
7.Display month by name and number
9.Use relative indexes to simplify the creation of a custom time and date format.
10.Date Format with LocaleDate Format with Locale
11.Date Format SymbolsDate Format Symbols
12.Decimal Format with different SymbolsDecimal Format with different Symbols
13.Date format: "dd.MM.yy", "yyyy.MM.dd G 'at' hh:mm:ss z","EEE, MMM d, ''yy", "h:mm a", "H:mm", "H:mm:ss:SSS", "K:mm a,z","yyyy.MMMMM.dd GGG hh:mm aaa"Date format:
16.This is same as MEDIUM: DateFormat.getDateInstance().format(new Date())
17.This is same as MEDIUM: DateFormat.getDateInstance(DateFormat.DEFAULT).format(new Date())
18.DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA).format(new Date())
19.DateFormat.getTimeInstance(DateFormat.LONG, Locale.CANADA).format(new Date())
20.DateFormat.getTimeInstance(DateFormat.FULL, Locale.CANADA).format(new Date())
21.DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.CANADA).format(new Date())
25.Parse date string input with DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.CANADA)
26.Simple Date Format DemoSimple Date Format Demo
27.Format date in Medium format
28.Format date in Long format
29.Format date in Full format
30.Format date in Default format
31.Formatting day of week using SimpleDateFormat
32.Formatting day of week in EEEE format like Sunday, Monday etc.
33.Formatting day in d format like 1,2 etc
34.Formatting day in dd format like 01, 02 etc.
35.Format hour in h (1-12 in AM/PM) format like 1, 2..12.
36.Format hour in hh (01-12 in AM/PM) format like 01, 02..12.
37.Format hour in H (0-23) format like 0, 1...23.
38.Format hour in HH (00-23) format like 00, 01..23.
39.Format hour in k (1-24) format like 1, 2..24.
40.Format hour in kk (01-24) format like 01, 02..24.
41.Format hour in K (0-11 in AM/PM) format like 0, 1..11.
42.Format hour in KK (00-11) format like 00, 01,..11.
43.Formatting minute in m format like 1,2 etc.
44.Format minutes in mm format like 01, 02 etc.
45.Format month in M format like 1,2 etc
46.Format Month in MM format like 01, 02 etc.
47.Format Month in MMM format like Jan, Feb etc.
48.Format Month in MMMM format like January, February etc.
49.Format seconds in s format like 1,2 etc.
50.Format seconds in ss format like 01, 02 etc.
51.Format date in dd/mm/yyyy format
52.Format date in mm-dd-yyyy hh:mm:ss format
53.Format year in yy format like 07, 08 etc
54.Format year in yyyy format like 2007, 2008 etc. SimpleDateFormat("hh") SimpleDateFormat("H") // The hour (0-23) SimpleDateFormat("m"): The minutes SimpleDateFormat("mm")
59.SimpleDateFormat("MM"): number based month value SimpleDateFormat("s"): The seconds SimpleDateFormat("ss") SimpleDateFormat("a"): The am/pm marker SimpleDateFormat("z"): The time zone SimpleDateFormat("zzzz") SimpleDateFormat("Z") SimpleDateFormat("hh:mm:ss a") SimpleDateFormat("") SimpleDateFormat("HH:mm:ss Z")
71.SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z")
73.The month: SimpleDateFormat("M")
74.Three letter-month value: SimpleDateFormat("MMM")
75.Full length of month name: SimpleDateFormat("MMMM")
76.The day number: SimpleDateFormat("d")
77.Two digits day number: SimpleDateFormat("dd")
78.The day in week: SimpleDateFormat("E")
79.Full day name: SimpleDateFormat("EEEE")
80.Add AM PM to time using SimpleDateFormat
81.Simply format a date as "YYYYMMDD"
82.Java SimpleDateFormat Class Example("MM/dd/yyyy")
83.The format used is EEE, dd MMM yyyy HH:mm:ss Z in US locale.
84.Date Formatting and Localization
85.Get a List of Short Month Names
86.Get a List of Weekday Names
87.Get a List of Short Weekday Names
88.Change date formatting symbols
89.An alternate way to get week days symbols
90.ISO8601 formatter for date-time without time zone.The format used is yyyy-MM-dd'T'HH:mm:ss.
91.ISO8601 formatter for date-time with time zone. The format used is yyyy-MM-dd'T'HH:mm:ssZZ.
92.Parsing custom formatted date string into Date object using SimpleDateFormat
93.Parse with a custom format
94.Parsing the Time Using a Custom Format
95.Parse with a default format
96.Parse a date and time
97.Parse string date value input with SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z")
98.Parse string date value input with SimpleDateFormat("dd-MMM-yy")
99.Parse string date value with default format: DateFormat.getDateInstance(DateFormat.DEFAULT)
100.Find the current date format
101.Time format viewer
102.Date format viewer
103.Returns a String in the format Xhrs, Ymins, Z sec, for the time difference between two times
104.format Duration
105.Get Date Suffix
106.Date Format Cache
107.ISO8601 Date Format
108.Explode a date in 8 digit format into the three components.
109.Date To Iso Date Time
110.Iso Date Time To Date
111.Gets formatted time
112.Format Time To 2 Digits
113.Time formatting utility.
114.ISO 8601 BASIC date format
115.Format As MySQL Datetime SimpleDateFormat( "EEE MMM d HH:mm:ss z yyyy", Locale.UK )
117.Date parser for the ISO 8601 format.
118.Pack/Unpacks date stored in kdb format
119.Provides preset formatting for Dates. All dates are returned as GMT
120.Parse RSS date format to Date object.
121.Date format for face book
122.FastDateFormat is a fast and thread-safe version of java.text.SimpleDateFormat.
123.Date format and parse Util
124.XSD Date Time
125.Return a String value of Now() in a specify format
126.Format data to string with specified style.
127.extends Formatter