Playing with Dates in Java

I always forget how to do these things so I thought I should write it down.

Changing Dates:

Here is an example of getting the date for seven days ago from now.

    Calendar sevenDaysAgo = Calendar.getInstance();
    sevenDaysAgo.add(Calendar.DATE, -7);
    sevenDaysAgo.set(Calendar.HOUR_OF_DAY, 0);
    sevenDaysAgo.set(Calendar.MINUTE, 0);
    sevenDaysAgo.set(Calendar.SECOND, 0);
    sevenDaysAgo.set(Calendar.MILLISECOND, 0);

Formatting Dates:

Here is the simple way to format a date and time.

    DateFormat.getDateTimeInstance().format(sevenDaysAgo.getTime()))

The output is:

    May 21, 2008 12:00:00 AM

Note that according to the JavaDoc, DateFormats are inherently unsafe for multithreaded use. You should not make a call to a static instance of a DateFormat nor share a single instance across thread boundaries without proper synchronization.  The same applies to Calendar.  For more information on this see Sun Bug #6231579 and Sun Bug #6178997.

Creating Dates:

Here is an example of creating a date, the birth date January 1, 1970.

    Calendar birthDate = Calendar.getInstance();
    birthDate.clear();
    birthDate.set(Calendar.YEAR, 1970);
    birthDate.set(Calendar.MONTH, 0);
    birthDate.set(Calendar.DATE, 1);

For further reading please Create a Date object using the Calendar class and of course the JavaDocs for Calendar, Date and DateFormat.

Leave a Reply

Your email address will not be published. Required fields are marked *