Thursday, July 9, 2009

Creating a minimum and a maximum Date for a Calendar

If there is one thing I hate it's to work with dates. Not that it's hard or so. Just if you want to work with the java core classes it's sometimes a hassle.

For example I needed the minimum and maximum date for a day. After a lot of googleling I came up with a simple? solution.


Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();

c1.set(Calendar.AM_PM,Calendar.AM);
c1.set(Calendar.HOUR, c1.getActualMinimum(Calendar.HOUR));
c1.set(Calendar.MINUTE, c1.getActualMinimum(Calendar.MINUTE));
c1.set(Calendar.SECOND, c1.getActualMinimum(Calendar.SECOND));
c1.set(Calendar.MILLISECOND, c1.getActualMinimum(Calendar.MILLISECOND));

c2.set(Calendar.AM_PM,Calendar.PM);
c2.set(Calendar.HOUR, c2.getActualMaximum(Calendar.HOUR));
c2.set(Calendar.MINUTE, c2.getActualMaximum(Calendar.MINUTE));
c2.set(Calendar.SECOND, c2.getActualMaximum(Calendar.SECOND));
c2.set(Calendar.MILLISECOND, c2.getActualMaximum(Calendar.MILLISECOND));

Date first = c1.getTime();
Date last = c2.getTime();


Result:

Tue Jul 07 00:00:00 PDT 2009
Tue Jul 07 23:59:59 PDT 2009

The important part is here:


c1.set(Calendar.AM_PM,Calendar.AM);


if you don't specify AM/PM you end up with:

Tue Jul 07 12:00:00 PDT 2009

which is a bit annoying...

No comments:

Post a Comment