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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DateUtil extends BaseUtil {
private static Log log = LogFactory.getLog(DateUtil.class);
private static String datePattern = "MM/dd/yyyy";
private static String timePattern = datePattern + " HH:MM a";
private static String defaultDatePattern = "EEE MMM dd HH:MM:ss z yyyy";
public static String getDatePattern() {
return datePattern;
}
public static final String getDate(Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";
if (aDate != null) {
df = new SimpleDateFormat(datePattern);
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) {
if (log.isDebugEnabled()) {
log.debug("conversion failed, trying default date format");
}
df = new SimpleDateFormat(defaultDatePattern);
try {
date = df.parse(strDate);
} catch (ParseException pe2) {
throw new ParseException(pe2.getMessage(), pe2.getErrorOffset());
}
if (log.isDebugEnabled()) {
log.debug("formatted date successfully!");
}
}
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(datePattern);
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(datePattern, aDate);
}
public static Date convertStringToDate(String strDate)
throws ParseException {
Date aDate = null;
try {
if (log.isDebugEnabled()) {
log.debug("converting date with pattern: " + datePattern);
}
aDate = convertStringToDate(datePattern, 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;
}
}