package hirondelle.web4j.config;
import java.util.*;
import java.text.*;
import java.util.regex.*;
import hirondelle.web4j.model.DateTime;
import hirondelle.web4j.request.DateConverter;
public final class DateConverterImpl implements DateConverter {
public String formatEyeFriendlyDateTime(DateTime aDateTime, Locale aLocale){
return aDateTime.format("YYYY/MM/DD");
}
public DateTime parseEyeFriendlyDateTime(String aInputValue, Locale aLocale){
return parseDateTime(aInputValue, EYE_FRIENDLY_REGEX);
}
public DateTime parseHandFriendlyDateTime(String aInputValue, Locale aLocale){
return parseDateTime(aInputValue, HAND_FRIENDLY_REGEX);
}
public String formatEyeFriendly(Date aDate, Locale aLocale, TimeZone aTimeZone) {
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
format.setTimeZone(aTimeZone);
String result = format.format(aDate);
return result;
}
public Date parseHandFriendly(String aInputValue, Locale aLocale, TimeZone aTimeZone) {
return parse(aInputValue, HAND_FRIENDLY_REGEX, aTimeZone);
}
public Date parseEyeFriendly(String aInputValue, Locale aLocale, TimeZone aTimeZone) {
return parse(aInputValue, EYE_FRIENDLY_REGEX, aTimeZone);
}
private static final String MONTH =
"(01|02|03|04|05|06|07|08|09|10|11|12)"
;
private static final String DAY_OF_MONTH =
"(01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)"
;
private static final Pattern HAND_FRIENDLY_REGEX =
Pattern.compile("(\\d\\d\\d\\d)" + MONTH + DAY_OF_MONTH)
;
private static final Pattern EYE_FRIENDLY_REGEX =
Pattern.compile("(\\d\\d\\d\\d)" + "/" + MONTH + "/" + DAY_OF_MONTH)
;
private Date parse(String aInputValue, Pattern aRegex, TimeZone aTimeZone){
Date result = null;
Matcher matcher = aRegex.matcher(aInputValue);
if( matcher.matches() ) {
Integer year = new Integer( matcher.group(1) );
Integer month = new Integer(matcher.group(2));
Integer day = new Integer(matcher.group(3));
Calendar cal = new GregorianCalendar(year.intValue(), month.intValue() - 1, day.intValue(), 0,0,0);
cal.setTimeZone(aTimeZone);
result = cal.getTime();
}
return result;
}
private static final class DateTimeParts {
String year;
String month;
String day;
}
private DateTime parseDateTime(String aInputValue, Pattern aRegex){
DateTime result = null;
Matcher matcher = aRegex.matcher(aInputValue);
if( matcher.matches() ) {
DateTimeParts parts = getParts(matcher);
Integer year = new Integer(parts.year);
Integer month = new Integer(parts.month);
Integer day = new Integer(parts.day);
result = DateTime.forDateOnly(year, month, day);
}
return result;
}
private DateTimeParts getParts(Matcher aMatcher){
DateTimeParts result = new DateTimeParts();
result.year = aMatcher.group(1);
result.month = aMatcher.group(2);
result.day = aMatcher.group(3);
return result;
}
}