Created
September 29, 2011 16:30
-
-
Save codebox/1251175 to your computer and use it in GitHub Desktop.
Java class that fixes a number of SimpleDateFormat annoyances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.DateFormat; | |
import java.text.ParseException; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
/** | |
* Helper class providing a thread-safe, null-safe wrapper around a DateFormat | |
* object configured to perform 'strict' (i.e. non-lenient) date parsing. | |
* | |
* @author rob.dawson | |
*/ | |
public class StrictDateFormat { | |
private final DateFormat dateFormat; | |
private final String formatString; | |
/** | |
* Initialises the instance. | |
* | |
* @param formatString the format string to be used for String/Date conversion | |
* @throws IllegalArgumentException is the specified String is not a valid date format | |
*/ | |
public StrictDateFormat(final String formatString) { | |
this.formatString = formatString; | |
dateFormat = new SimpleDateFormat(formatString); | |
dateFormat.setLenient(false); | |
} | |
/** | |
* Attempts to convert the specified text into a Date object using the | |
* format string for this instance. | |
* | |
* @param dateText the String to be converted to a date | |
* @return a Date object obtained by parsing the specified string, or null if the dateText argument is null | |
* @throws IllegalArgumentException is the specified String is not a valid date | |
*/ | |
public Date parse(final String dateText) { | |
if (dateText == null) { | |
return null; | |
} else { | |
try { | |
synchronized (dateFormat) { | |
return dateFormat.parse(dateText); | |
} | |
} catch (ParseException ex) { | |
throw new IllegalArgumentException( | |
String.format( | |
"Unable to convert the text '%1$s' into a Date using the format '%2$s'. The error message was %3$s", | |
dateText, formatString, ex.getMessage())); | |
} | |
} | |
} | |
/** | |
* Formats the specified Date object into a String conforming to the format | |
* string for this instance. | |
* | |
* @param date Date object to be formatted | |
* @return a String representation of the date argument, or null if the date argument is null | |
*/ | |
public String format(final Date date) { | |
if (date == null) { | |
return null; | |
} else { | |
synchronized (dateFormat) { | |
return dateFormat.format(date); | |
} | |
} | |
} | |
@Override | |
public String toString() { | |
return formatString; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment