Home | FAQ | Contact me

Date/time stuff in Java

Here's a quick crib sheet on Date and timestamping. There's a table at the end of formatting conversion specifiers.

Warning: There is a decorator class, java.sql.Date, that wraps the one we're discussing here java.util.Date. Both of these classes contain large numbers of deprecated methods. Beware, therefore. Look around, notably at java.util.Calendar for solutions to this.

The basic code

Here's how to pick up the current date from Java. Insert this into your favorite class, step back and behold:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class X
{
	public static void main( String[] args )
	{
		Date		date       = new Date();
		DateFormat	dateformat = DateFormat.getDateInstance( DateFormat.DEFAULT );
		String		string     = dateformat.format( date );

		System.out.println( "DEFAULT: " + string );

		dateformat = DateFormat.getDateInstance( DateFormat.FULL );
		string     = dateformat.format( date );
		System.out.println( "   FULL: " + string );

		dateformat = DateFormat.getDateInstance( DateFormat.LONG );
		string     = dateformat.format( date );
		System.out.println( "   LONG: " + string );

		dateformat = DateFormat.getDateInstance( DateFormat.MEDIUM );
		string     = dateformat.format( date );
		System.out.println( " MEDIUM: " + string );

		dateformat = DateFormat.getDateInstance( DateFormat.SHORT );
		string     = dateformat.format( date );
		System.out.println( "  SHORT: " + string );
	}
}

If today were 12 August 2009, you would see (in my locale):

DEFAULT: Aug 12, 2009 FULL: Tuesday, August 12, 2009 LONG: August 12, 2009 MEDIUM: Aug 12, 2009 SHORT: 8/12/09

What is time (date)?

Java time/date originated from Unix whose calendar time is defined to be "seconds since the Epoch" or "00:00:00: 1 January 1970 Universal Time Coordinated (UTC)". Therefore, time is expressable in seconds, milliseconds, actually, using these APIs. long is a very convenient way to store a timestamp.

Just insert the following code in the test main() above.

			try
			{
				long		calendar;
				DateFormat	formatter;

				string    = "11-June-07";
				formatter = new SimpleDateFormat( "dd-MMM-yy" );
				date      = ( Date ) formatter.parse( string );
				calendar  = date.getTime();

				System.out.println( "\nThis date, " + string + ", is " + calendar +"." );
			}
			catch( ParseException e )
			{
				System.out.println( "Exception: " + e );
			}

And, the output for this segment of code is:

This date, 11-June-2007, is 1181541600000.

Obtaining a Date from long

Last, add the following code onto the end of the other two sections and run it to see how to convert a date/timestamp from long into Date and print out just as was done earlier. But first, add 3 hours and 21 minutes so that our answer is more interesting and we demonstrate timestamp arithmetic. Remember, we're working in milliseconds here.

long	add3hrs21mins = 1000 * 60 * 60 * 3 + 1000 * 60 * 21;

calendar += add3hrs21mins;

Date	fromLong = new Date( new Long( calendar ) );

formatter = new SimpleDateFormat( "EEE, dd-MMM-yyyy HH:mm:ss" );
string    = formatter.format( fromLong );

System.out.println( "\nThat timestamp (" + calendar + ") is now: " + string );

Output:

That timestamp (1181553660000) is now: Mon, 11-Jun-2007 03:21:00

java.sql.Date

The most important and useful method of this class is valueOf() and it's not deprecated. An instance of this class is more useful in a SQL setting. An example here of converting between java.sql.Date and java.util.Date can be found here. Actually, we're using java.util.Calendar instead of java.util.Date. This code was taken from a JUnit 4 test.

import java.sql.Date;
import java.util.Calendar;

import org.junit.BeforeClass;

public class FunTest
{
    private static Date fabricateDate( int year, int month, int day )
    {
        Calendar calendar = Calendar.getInstance();

        calendar.set( Calendar.YEAR,  year    );
        calendar.set( Calendar.MONTH, month-1 );  // (just as C's time.h interfaces)
        calendar.set( Calendar.DATE,  day     );

        long     milliseconds = calendar.getTimeInMillis();

        return new Date( milliseconds );
    }

    @BeforeClass
    public static void setUpBeforeClass() throws Exception
    {
        Date  date;

		    date = Date.valueOf( "2010-10-14" );
		    System.out.println( date );

		    date = fabricateDate( 2010, 10, 14 );
		    System.out.println( date );

These two ways of establishing a date then printing it out yield the same result:

2010-10-14 2010-10-14

Appendix: Formatting conversion specifiers table

This is how the string, "EEE, dd-MMM-yyyy HH:mm:ss" (in earlier examples) is composed. Note that the standard representation in the United States is "EEEE, MMMM dd, yyyy hh:mm a" or:

That timestamp (1181553660000) is now: Monday, June 11, 2007 3:21 AM

Here's the table:

Symbol Meaning Example
this becomes:
y year yy
yyyy
03
2003
M month M
MM
MMM
MMMM
12
07
Jul
December
h hour (1-12, AM/PM) h
hh
3
03
H hour (0-23) H
HH
15
15
k hour (1-24) k
kk
3
03
K hour (0-11 AM/PM) K
KK
15
15
m minutes m
mm
mmm
7
15
15
s seconds s
ss
15
15
S milliseconds (0-999) SSS 007
E day in week EEE
EEEE
Tue
Tuesday
d day in month d
dd
3
03
D day in year (1-365 or 1-364) D
DDD
65
065
F day of week in month (1-5) F 1
w week in year (1-53) w 7
W week in month (1-5) W 3
a AM/PM designator a
aa
AM
AM
z time zone z
zzz
zzzz
MST
MST
Mountain Standard Time
G era GG AD
' escape text into output 'hour' h hour 9
" escape single quote into output "ss"SSS 45'876