| 1 | |
package liquibase.util; |
| 2 | |
|
| 3 | |
import java.sql.Time; |
| 4 | |
import java.text.ParseException; |
| 5 | |
import java.text.SimpleDateFormat; |
| 6 | |
import java.util.Date; |
| 7 | |
|
| 8 | 2 | public class ISODateFormat { |
| 9 | |
|
| 10 | 2 | private SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT_STRING); |
| 11 | 2 | private SimpleDateFormat dateTimeFormatWithDecimal = new SimpleDateFormat(DATE_TIME_FORMAT_STRING_WITH_DECIMAL); |
| 12 | 2 | private SimpleDateFormat dateTimeFormatWithSpace = new SimpleDateFormat(DATE_TIME_FORMAT_STRING_WITH_SPACE); |
| 13 | 2 | private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); |
| 14 | 2 | private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); |
| 15 | |
private static final String DATE_TIME_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss"; |
| 16 | |
private static final String DATE_TIME_FORMAT_STRING_WITH_SPACE = "yyyy-MM-dd HH:mm:ss"; |
| 17 | |
private static final String DATE_TIME_FORMAT_STRING_WITH_DECIMAL = "yyyy-MM-dd'T'HH:mm:ss.S"; |
| 18 | |
|
| 19 | |
public String format(java.sql.Date date) { |
| 20 | 0 | return dateFormat.format(date); |
| 21 | |
} |
| 22 | |
|
| 23 | |
public String format(java.sql.Time date) { |
| 24 | 0 | return timeFormat.format(date); |
| 25 | |
} |
| 26 | |
|
| 27 | |
public String format(java.sql.Timestamp date) { |
| 28 | 0 | return dateTimeFormatWithDecimal.format(date); |
| 29 | |
} |
| 30 | |
|
| 31 | |
public String format(Date date) { |
| 32 | 0 | if (date instanceof java.sql.Date) { |
| 33 | 0 | return format(((java.sql.Date) date)); |
| 34 | 0 | } else if (date instanceof Time) { |
| 35 | 0 | return format(((java.sql.Time) date)); |
| 36 | 0 | } else if (date instanceof java.sql.Timestamp) { |
| 37 | 0 | return format(((java.sql.Timestamp) date)); |
| 38 | |
} else { |
| 39 | 0 | throw new RuntimeException("Unknown type: " + date.getClass().getName()); |
| 40 | |
} |
| 41 | |
} |
| 42 | |
|
| 43 | |
public Date parse(String dateAsString) throws ParseException { |
| 44 | 2 | SimpleDateFormat dateTimeFormat = this.dateTimeFormat; |
| 45 | |
|
| 46 | 2 | if (dateAsString.indexOf('.') >= 0) { |
| 47 | 0 | dateTimeFormat = this.dateTimeFormatWithDecimal; |
| 48 | 2 | } else if (dateAsString.indexOf(' ') >= 0) { |
| 49 | 0 | dateTimeFormat = this.dateTimeFormatWithSpace; |
| 50 | |
} |
| 51 | |
|
| 52 | 2 | if (dateAsString.length() != dateFormat.toPattern().length() |
| 53 | |
&& dateAsString.length() != timeFormat.toPattern().length()) { |
| 54 | 1 | return new java.sql.Timestamp(dateTimeFormat.parse(dateAsString).getTime()); |
| 55 | |
} else { |
| 56 | 1 | if (dateAsString.indexOf(':') > 0) { |
| 57 | 0 | return new java.sql.Time(timeFormat.parse(dateAsString).getTime()); |
| 58 | |
} else { |
| 59 | 1 | return new java.sql.Date(dateFormat.parse(dateAsString).getTime()); |
| 60 | |
} |
| 61 | |
} |
| 62 | |
} |
| 63 | |
} |