Monday, March 3, 2008

Working with Date and Time in Java

I recalled when I started to learn Java, one of the burden I'm facing with is how to deal with date and time properly.

So to help anyone with the same problem, in this article I list down a number of "shortcut tips" on dealing with them.

1. Returning timestamp
Date now = new Date();

long nowLong = now.getTime(); //returning a timestamp
System.out.println("Value is " + nowLong);

2. Formatting date
SimpleDateFormat df = new java.text.SimpleDateFormat("MM/dd/yyyy");
Date now = new Date();
long nowLong = now.getTime(); //returning a timestamp

System.out.println(df.format(now));

3. Assigning date value with a formatted text literal
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

try {
Date date = (Date) sdf.parse("12/31/2007");
System.out.println("Current date is : " + sdf.format(date));
} catch (ParseException e) {
System.out.print("Illegal date !");
}

4. Comparing date with compareTo() method of Date object
//With compareTo() method we should have a return of value -1, 0, and 1.
//Syntax : date1.compareTo(date2);
//Return value
//   -1 : date1 is earlier than date2
//    0 : date1 is having exactly same value with date2
//    1 : date2 is later than date2

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

try {
Date date1 = (Date) sdf.parse("12/31/2007");
Date date2 = (Date) sdf.parse("12/31/2008");
Date date3 = (Date) sdf.parse("12/31/2008");

System.out.println(date1.compareTo(date2));
System.out.println(date2.compareTo(date1));
System.out.println(date2.compareTo(date3));
} catch (ParseException e) {
System.out.print("Illegal date !");
}

5. Assigning date with GregorianCalendar class
//Get current date and time
Calendar cal = new GregorianCalendar();
System.out.println(cal);

//Set date with int value
Calendar newdate = new GregorianCalendar(2008, Calendar.MARCH, 1);
System.out.println(newdate);

//Convert into Date object
Date date = newdate.getTime();     
System.out.println(date);

//Print with a MM/dd/yyyy format
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("New date is : " + sdf.format(date));

Online Resources:
1. http://www.javaworld.com/jw-12-2000/jw-1229-dates.html
2. http://www.javaworld.com/javaworld/jw-03-2001/jw-0330-time.html
3. http://forum.java.sun.com/thread.jspa?threadID=552315&messageID=2701323
4. http://forum.java.sun.com/thread.jspa?threadID=539302&range=1&start=2&forumID=31
5. http://www.exampledepot.com/

2 comments:

Adri said...

mas, itu kok waktu instansiasi Calendar, kok constructor yang dipanggil malah GregorianCalendar sih ? Bukannya constructor yg dipakai yg Calendar ya?

Adri said...

import nya pakai apa ya mas?