| « UTM Coordinate Converter Available | Using Wink to create Screen Casts » |
Introduction to working with Java dates
Many new Java developers often struggle with how to deal with dates in Java. In the article, I will give a quick primer on how to easily work with dates.
In Java, a date/time is stored internally as the number of milliseconds since January 1, 1970 UTC; this is often referred to as the Epoch. So, when creating a Date object, the constructor is a long. To create a Date object with the current date and time, use the empty constructor.
import java.util.Date;
Date myDate = new Date(); //creates Date object using the current date and time
To display a Date in a format a user can read, the SimpleDateFormat class comes into play. To use SimpleDateFormat, you specify a pattern for the date. The various pattern letters are defined in the Java API documentation.
Examples:
"yyyy-MM-dd" would produce something like 2009-11-26
"MMMM dd, yyyy HH:mm" would produce something like November 26, 2009 21:03
So to display you Date you first create an instance of a SimpleDateFormat, and use that to create a String:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");String formattedDate = dateFormat.format(myDate);
The SimpleDateFormat class can also be used to create a Date object from a String:
Date newDate = dateFormat.parse("1969-10-15");
The above produces a new Date object set to October 15, 1969.
There a many more complexities with date and times, such as dealing with time zones, calcuating differences between dates, etc. but this should hopefully provide a good starting point.
For a handy tool, to convert between Java timestamps and formatted Dates incorporating different time zones, try Timestamp Converter
Trackback address for this post
Trackback URL (right click and copy shortcut/link location)