ISO8601 Date Format
//revised from skaringa
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* Format and parse an ISO 8601 DateFormat used in XML documents.
* The lexical representation for date is the reduced (right truncated)
* lexical representation for dateTime: CCYY-MM-DD.
* No left truncation is allowed.
* An optional following time zone qualifier is allowed as for dateTime.
*/
public class ISO8601DateFormat extends ISO8601DateTimeFormat {
/**
* Construct a new ISO8601DateFormat using the default time zone.
*
*/
public ISO8601DateFormat() {
setCalendar(Calendar.getInstance());
}
/**
* Construct a new ISO8601DateFormat using a specific time zone.
* @param tz The time zone used to format and parse the date.
*/
public ISO8601DateFormat(TimeZone tz) {
setCalendar(Calendar.getInstance(tz));
}
/**
* @see java.text.DateFormat#parse(String, ParsePosition)
*/
public Date parse(String text, ParsePosition pos) {
int i = pos.getIndex();
try {
int year = Integer.valueOf(text.substring(i, i + 4)).intValue();
i += 4;
if (text.charAt(i) != '-') {
throw new NumberFormatException();
}
i++;
int month = Integer.valueOf(text.substring(i, i + 2)).intValue() - 1;
i += 2;
if (text.charAt(i) != '-') {
throw new NumberFormatException();
}
i++;
int day = Integer.valueOf(text.substring(i, i + 2)).intValue();
i += 2;
calendar.set(year, month, day);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0); // no parts of a second
i = parseTZ(i, text);
}
catch (NumberFormatException ex) {
pos.setErrorIndex(i);
return null;
}
catch (IndexOutOfBoundsException ex) {
pos.setErrorIndex(i);
return null;
}
finally {
pos.setIndex(i);
}
return calendar.getTime();
}
/**
* @see java.text.DateFormat#format(Date, StringBuffer, FieldPosition)
*/
public StringBuffer format(
Date date,
StringBuffer sbuf,
FieldPosition fieldPosition) {
calendar.setTime(date);
writeCCYYMM(sbuf);
//writeTZ(sbuf);
return sbuf;
}
}
/**
* Format and parse an ISO 8601 DateTimeFormat used in XML documents.
* This lexical representation is the ISO 8601
* extended format CCYY-MM-DDThh:mm:ss
* where "CC" represents the century, "YY" the year, "MM" the month
* and "DD" the day,
* preceded by an optional leading "-" sign to indicate a negative number.
* If the sign is omitted, "+" is assumed.
* The letter "T" is the date/time separator
* and "hh", "mm", "ss" represent hour, minute and second respectively.
* This representation may be immediately followed by a "Z" to indicate
* Coordinated Universal Time (UTC) or, to indicate the time zone,
* i.e. the difference between the local time and Coordinated Universal Time,
* immediately followed by a sign, + or -,
* followed by the difference from UTC represented as hh:mm.
*
*/
class ISO8601DateTimeFormat extends DateFormat {
/**
* Construct a new ISO8601DateTimeFormat using the default time zone.
*
*/
public ISO8601DateTimeFormat() {
setCalendar(Calendar.getInstance());
}
/**
* Construct a new ISO8601DateTimeFormat using a specific time zone.
* @param tz The time zone used to format and parse the date.
*/
public ISO8601DateTimeFormat(TimeZone tz) {
setCalendar(Calendar.getInstance(tz));
}
/**
* @see DateFormat#parse(String, ParsePosition)
*/
public Date parse(String text, ParsePosition pos) {
int i = pos.getIndex();
try {
int year = Integer.valueOf(text.substring(i, i + 4)).intValue();
i += 4;
if (text.charAt(i) != '-') {
throw new NumberFormatException();
}
i++;
int month = Integer.valueOf(text.substring(i, i + 2)).intValue() - 1;
i += 2;
if (text.charAt(i) != '-') {
throw new NumberFormatException();
}
i++;
int day = Integer.valueOf(text.substring(i, i + 2)).intValue();
i += 2;
if (text.charAt(i) != 'T') {
throw new NumberFormatException();
}
i++;
int hour = Integer.valueOf(text.substring(i, i + 2)).intValue();
i += 2;
if (text.charAt(i) != ':') {
throw new NumberFormatException();
}
i++;
int mins = Integer.valueOf(text.substring(i, i + 2)).intValue();
i += 2;
int secs = 0;
if (i < text.length() && text.charAt(i) == ':') {
// handle seconds flexible
i++;
secs = Integer.valueOf(text.substring(i, i + 2)).intValue();
i += 2;
}
calendar.set(year, month, day, hour, mins, secs);
calendar.set(Calendar.MILLISECOND, 0); // no parts of a second
i = parseTZ(i, text);
}
catch (NumberFormatException ex) {
pos.setErrorIndex(i);
return null;
}
catch (IndexOutOfBoundsException ex) {
pos.setErrorIndex(i);
return null;
}
finally {
pos.setIndex(i);
}
return calendar.getTime();
}
/**
* Parse the time zone.
* @param i The position to start parsing.
* @param text The text to parse.
* @return The position after parsing has finished.
*/
protected final int parseTZ(int i, String text) {
if (i < text.length()) {
// check and handle the zone/dst offset
int offset = 0;
if (text.charAt(i) == 'Z') {
offset = 0;
i++;
}
else {
int sign = 1;
if (text.charAt(i) == '-') {
sign = -1;
}
else if (text.charAt(i) != '+') {
throw new NumberFormatException();
}
i++;
int offsetHour = Integer.valueOf(text.substring(i, i + 2)).intValue();
i += 2;
if (text.charAt(i) != ':') {
throw new NumberFormatException();
}
i++;
int offsetMin = Integer.valueOf(text.substring(i, i + 2)).intValue();
i += 2;
offset = ((offsetHour * 60) + offsetMin) * 60000 * sign;
}
int offsetCal =
calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
calendar.add(Calendar.MILLISECOND, offsetCal - offset);
}
return i;
}
/**
* @see DateFormat#format(Date, StringBuffer, FieldPosition)
*/
public StringBuffer format(
Date date,
StringBuffer sbuf,
FieldPosition fieldPosition) {
calendar.setTime(date);
writeCCYYMM(sbuf);
sbuf.append('T');
writehhmmss(sbuf);
writeTZ(sbuf);
return sbuf;
}
/**
* Write the time zone string.
* @param sbuf The buffer to append the time zone.
*/
protected final void writeTZ(StringBuffer sbuf) {
int offset =
calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
if (offset == 0) {
sbuf.append('Z');
}
else {
int offsetHour = offset / 3600000;
int offsetMin = (offset % 3600000) / 60000;
if (offset >= 0) {
sbuf.append('+');
}
else {
sbuf.append('-');
offsetHour = 0 - offsetHour;
offsetMin = 0 - offsetMin;
}
appendInt(sbuf, offsetHour, 2);
sbuf.append(':');
appendInt(sbuf, offsetMin, 2);
}
}
/**
* Write hour, minutes, and seconds.
* @param sbuf The buffer to append the string.
*/
protected final void writehhmmss(StringBuffer sbuf) {
int hour = calendar.get(Calendar.HOUR_OF_DAY);
appendInt(sbuf, hour, 2);
sbuf.append(':');
int mins = calendar.get(Calendar.MINUTE);
appendInt(sbuf, mins, 2);
sbuf.append(':');
int secs = calendar.get(Calendar.SECOND);
appendInt(sbuf, secs, 2);
}
/**
* Write century, year, and months.
* @param sbuf The buffer to append the string.
*/
protected final void writeCCYYMM(StringBuffer sbuf) {
int year = calendar.get(Calendar.YEAR);
appendInt(sbuf, year, 4);
String month;
switch (calendar.get(Calendar.MONTH)) {
case Calendar.JANUARY :
month = "-01-";
break;
case Calendar.FEBRUARY :
month = "-02-";
break;
case Calendar.MARCH :
month = "-03-";
break;
case Calendar.APRIL :
month = "-04-";
break;
case Calendar.MAY :
month = "-05-";
break;
case Calendar.JUNE :
month = "-06-";
break;
case Calendar.JULY :
month = "-07-";
break;
case Calendar.AUGUST :
month = "-08-";
break;
case Calendar.SEPTEMBER :
month = "-09-";
break;
case Calendar.OCTOBER :
month = "-10-";
break;
case Calendar.NOVEMBER :
month = "-11-";
break;
case Calendar.DECEMBER :
month = "-12-";
break;
default :
month = "-NA-";
break;
}
sbuf.append(month);
int day = calendar.get(Calendar.DAY_OF_MONTH);
appendInt(sbuf, day, 2);
}
/**
* Write an integer value with leading zeros.
* @param buf The buffer to append the string.
* @param value The value to write.
* @param length The length of the string to write.
*/
protected final void appendInt(StringBuffer buf, int value, int length) {
int len1 = buf.length();
buf.append(value);
int len2 = buf.length();
for (int i = len2; i < len1 + length; ++i) {
buf.insert(len1, '0');
}
}
}
Related examples in the same category
1. | Date 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 | | |
8. | DateFormat.getDateInstance(DateFormat.SHORT) | | |
9. | Use relative indexes to simplify the creation of a custom time and date format. | | |
10. | Date Format with Locale | | |
11. | Date Format Symbols | | |
12. | Decimal 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" | | |
14. | SimpleDateFormat.getAvailableLocales | | |
15. | DateFormat.SHORT | | |
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()) | | |
22. | DateFormat.getDateInstance(DateFormat.LONG) | | |
23. | DateFormat.getTimeInstance(DateFormat.SHORT) | | |
24. | DateFormat.getTimeInstance(DateFormat.LONG) | | |
25. | Parse date string input with DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.CANADA) | | |
26. | Simple 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. | | |
55. | new SimpleDateFormat("hh") | | |
56. | new SimpleDateFormat("H") // The hour (0-23) | | |
57. | new SimpleDateFormat("m"): The minutes | | |
58. | new SimpleDateFormat("mm") | | |
59. | SimpleDateFormat("MM"): number based month value | | |
60. | new SimpleDateFormat("s"): The seconds | | |
61. | new SimpleDateFormat("ss") | | |
62. | new SimpleDateFormat("a"): The am/pm marker | | |
63. | new SimpleDateFormat("z"): The time zone | | |
64. | new SimpleDateFormat("zzzz") | | |
65. | new SimpleDateFormat("Z") | | |
66. | new SimpleDateFormat("hh:mm:ss a") | | |
67. | new SimpleDateFormat("HH.mm.ss") | | |
68. | new SimpleDateFormat("HH:mm:ss Z") | | |
69. | SimpleDateFormat("MM/dd/yy") | | |
70. | SimpleDateFormat("dd-MMM-yy") | | |
71. | SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z") | | |
72. | SimpleDateFormat("yyyy") | | |
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. | Explode a date in 8 digit format into the three components. | | |
108. | Date To Iso Date Time | | |
109. | Iso Date Time To Date | | |
110. | Gets formatted time | | |
111. | Format Time To 2 Digits | | |
112. | Time formatting utility. | | |
113. | ISO 8601 BASIC date format | | |
114. | Format As MySQL Datetime | | |
115. | new SimpleDateFormat( "EEE MMM d HH:mm:ss z yyyy", Locale.UK ) | | |
116. | Date parser for the ISO 8601 format. | | |
117. | Parse W3C Date 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 | | |