Share

August 8, 2010

My Java CalendarUtill

With each project I start i always need a CalendarUtill  so here is mine .... I always need a to Date Stare/End and a quick way to convert a date to a calendar ... let me know if you know if any better ways to do it.

public class CalendarUtils {

    public static Calendar toCalendar(Date date) {
        if (date != null) {
            Calendar cal = new GregorianCalendar();
            cal.setTime(date);
            return cal;
        }
        return null;
    }

    public static Calendar toDateStart(Date date) {
        Calendar cal = toCalendar(date);
        if (cal != null) {
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
        }
        return cal;
    }

    public static Calendar toDateEnd(Date date) {
        Calendar cal = toCalendar(date);
        if (cal != null) {
            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            cal.set(Calendar.MILLISECOND, 59);
        }
        return cal;
    }

}