Java Reference
In-Depth Information
Solution #2
If you only need to obtain the current date without going into calendar details, use the
java.util.Date
class to generate a new
Date
object. Doing so will cause the new
Date
object to be equal to the current system date. In the following code, you can see
how easy it is to create a new Date object and obtain the current date:
Date date = new Date();
System.out.println(date);
System.out.println(date.getTime());
The result will be a
Date
object that contains the current date and time taken from
the system that the code is run on, including the time zone information, as shown fol-
lowing listing. The time is the number of milliseconds since January 1, 1970, 00:00:00
GMT.
Sat Sep 10 14:45:57 CDT 2011
1315683957625
Solution #3
If you need to be more precise regarding the calendar, use the
java.util.Calendar
class. Although working with the
Calendar
class will
make your code longer, the results are much more precise. The following code demon-
strates just a handful of the capabilities of using this class to obtain the current date:
Calendar gCal = Calendar.getInstance();
// Month is based upon a zero index, January is equal to
0,
// so we need to add one to the month for it to be in
// a standard format
int month = gCal.get(Calendar.MONTH) + 1;int day
= gCal.get(Calendar.DATE);
int yr = gCal.get(Calendar.YEAR);