betweenGo

Playing with Dates in Java

by Frank Kim on May.28, 2008, under Java SE

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.

  • Share/Bookmark

Related posts:

  1. ATG Date Tag Converter is Buggy
  2. Updating/Reading Dates
  3. RQLQueryRange does not sort dates correctly
  4. java.io.FileNotFoundException for valid URL
  5. Invalid column type SQLException with ATG Repository

:

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!