01: package liquibase.util;
02:
03: import liquibase.database.sql.ComputedDateValue;
04:
05: import java.sql.Time;
06: import java.text.ParseException;
07: import java.text.SimpleDateFormat;
08: import java.util.Date;
09:
10: public class ISODateFormat {
11:
12: private SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
13: DATE_TIME_FORMAT_STRING);
14: private SimpleDateFormat dateTimeFormatWithDecimal = new SimpleDateFormat(
15: DATE_TIME_FORMAT_STRING_WITH_DECIMAL);
16: private SimpleDateFormat timeFormat = new SimpleDateFormat(
17: "HH:mm:ss");
18: private SimpleDateFormat dateFormat = new SimpleDateFormat(
19: "yyyy-MM-dd");
20: private static final String DATE_TIME_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss";
21: private static final String DATE_TIME_FORMAT_STRING_WITH_DECIMAL = "yyyy-MM-dd'T'HH:mm:ss.S";
22:
23: public String format(java.sql.Date date) {
24: return dateFormat.format(date);
25: }
26:
27: public String format(java.sql.Time date) {
28: return timeFormat.format(date);
29: }
30:
31: public String format(java.sql.Timestamp date) {
32: return dateTimeFormatWithDecimal.format(date);
33: }
34:
35: public String format(Date date) {
36: if (date instanceof ComputedDateValue) {
37: return date.toString();
38: } else if (date instanceof java.sql.Date) {
39: return format(((java.sql.Date) date));
40: } else if (date instanceof Time) {
41: return format(((java.sql.Time) date));
42: } else if (date instanceof java.sql.Timestamp) {
43: return format(((java.sql.Timestamp) date));
44: } else {
45: throw new RuntimeException("Unknown type: "
46: + date.getClass().getName());
47: }
48: }
49:
50: public Date parse(String dateAsString) throws ParseException {
51: SimpleDateFormat dateTimeFormat = this .dateTimeFormat;
52: String DATE_TIME_FORMAT_STRING = ISODateFormat.DATE_TIME_FORMAT_STRING;
53:
54: if (dateAsString.indexOf('.') >= 0) {
55: dateTimeFormat = this .dateTimeFormatWithDecimal;
56: DATE_TIME_FORMAT_STRING = ISODateFormat.DATE_TIME_FORMAT_STRING_WITH_DECIMAL;
57: }
58:
59: if (dateAsString.length() >= DATE_TIME_FORMAT_STRING.length() - 2) { //subtract 2 to not count the 's
60: return new java.sql.Timestamp(dateTimeFormat.parse(
61: dateAsString).getTime());
62: } else {
63: if (dateAsString.indexOf(':') > 0) {
64: return new java.sql.Time(timeFormat.parse(dateAsString)
65: .getTime());
66: } else {
67: return new java.sql.Date(dateFormat.parse(dateAsString)
68: .getTime());
69: }
70: }
71: }
72: }
|