package net.sourceforge.calendardate; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * Formats and parses CalendarDates in a locale-sensitive manner based on a * pattern string.
* For example for a date representing June 12, 2004: * *

* The pattern and format rules are the same as for java.text.SimpleDateFormat, * except that only the following pattern letters are useful:

* * * * * * * *
Letter * Date Component * Examples *
G * Era designator * AD *
y * Year * 1996;96 *
M * Month in year * July;Jul;07 *
d * Day in month * 10 *
E * Day in week * Tuesday;Tue
* * @see java.text.SimpleDateFormat */ public class CalendarDateFormat { private SimpleDateFormat dateFormat; /** * Creates a format object based on the given date pattern. The resulting format * is NOT lenient (i.e. "32-Jan-2004" will result in a ParseException, rather than * returning 01-Jan-2004) * @param pattern the pattern string - see class doc for more information * @exception IllegalArgumentException if the given pattern is invalid */ public CalendarDateFormat(String pattern) { dateFormat = new SimpleDateFormat(pattern); dateFormat.setLenient(false); dateFormat.setTimeZone(TimeZone.getDefault()); } /** * Creates a format object based on the given simple date format. */ public CalendarDateFormat(SimpleDateFormat format) { dateFormat = (SimpleDateFormat) format.clone(); dateFormat.setTimeZone(TimeZone.getDefault()); } /** * Creates a text-based representation of the given date * @param date The date to be formatted * @return The String form of the given date */ public String format(CalendarDate date) { return dateFormat.format(date.toDate(dateFormat.getTimeZone())); } /** * Parses the given string to produce a CalendarDate. * * @param source The text to parse * @return A CalendarDate matching the given string * @throws java.text.ParseException If one of the following this true: *
    *
  1. The String doesn't match the format of this pattern *
  2. The date represented by source is outside the * valid CalendarDate range *
*/ public CalendarDate parse(String source) throws ParseException { TimeZone timeZone = dateFormat.getTimeZone(); Date instant = dateFormat.parse(source); if (CalendarDate.isOutsideRange(timeZone, instant)) { throw new ParseException("Date is outside CalendarDate range", 0); } return new CalendarDate(timeZone, instant); } }