package org.appfuse.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.Constants;
import org.springframework.context.i18n.LocaleContextHolder;
public class DateUtil {
private static Log log = LogFactory.getLog(DateUtil.class);
private static String defaultDatePattern = null;
private static String timePattern = "HH:mm";
public static String getDatePattern() {
Locale locale = LocaleContextHolder.getLocale();
try {
defaultDatePattern = ResourceBundle.getBundle(Constants.BUNDLE_KEY, locale)
.getString("date.format");
} catch (MissingResourceException mse) {
defaultDatePattern = "MM/dd/yyyy";
}
return defaultDatePattern;
}
public static String getDateTimePattern() {
return DateUtil.getDatePattern() + " HH:mm:ss.S";
}
public static final String getDate(Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";
if (aDate != null) {
df = new SimpleDateFormat(getDatePattern());
returnValue = df.format(aDate);
}
return (returnValue);
}
public static final Date convertStringToDate(String aMask, String strDate)
throws ParseException {
SimpleDateFormat df = null;
Date date = null;
df = new SimpleDateFormat(aMask);
if (log.isDebugEnabled()) {
log.debug("converting '" + strDate + "' to date with mask '"
+ aMask + "'");
}
try {
date = df.parse(strDate);
} catch (ParseException pe) {
throw new ParseException(pe.getMessage(), pe.getErrorOffset());
}
return (date);
}
public static String getTimeNow(Date theTime) {
return getDateTime(timePattern, theTime);
}
public static Calendar getToday() throws ParseException {
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat(getDatePattern());
String todayAsString = df.format(today);
Calendar cal = new GregorianCalendar();
cal.setTime(convertStringToDate(todayAsString));
return cal;
}
public static final String getDateTime(String aMask, Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";
if (aDate == null) {
log.error("aDate is null!");
} else {
df = new SimpleDateFormat(aMask);
returnValue = df.format(aDate);
}
return (returnValue);
}
public static final String convertDateToString(Date aDate) {
return getDateTime(getDatePattern(), aDate);
}
public static Date convertStringToDate(String strDate)
throws ParseException {
Date aDate = null;
try {
if (log.isDebugEnabled()) {
log.debug("converting date with pattern: " + getDatePattern());
}
aDate = convertStringToDate(getDatePattern(), strDate);
} catch (ParseException pe) {
log.error("Could not convert '" + strDate
+ "' to a date, throwing exception");
pe.printStackTrace();
throw new ParseException(pe.getMessage(),
pe.getErrorOffset());
}
return aDate;
}
}