Solving all the date and time problems is a tough job (different calendar systems, time zones, date formats, date arithmetic, leap seconds, ...). You will find several classes useful for handling times and dates.
java.util.Date- A common representation of dates.
java.util.Calendar- From the Java documentation: "Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on." This is a very useful class, and you will often use this in preference to Date in my (limited) experience.
java.text.SimpleDateFormat- Useful for both parsing and formatting dates.
There are a lot of details in some areas and you will want to consult the JDK documentation for the specifics, but here are a few simple solutions to common problems.
System.currentTimeMillis(), which avoids the overhead of creating a Calendar object. This returns a
longinteger value. For example,
long startTime = System.currentTimeMillis();This is not a useful way to get a time or date that is readable by humans, but is fine for figuring out how many seconds or milliseconds something took.
To get a string which has the current date and time in a fairly readable format, use the default conversion to String.
String rightNow = "" + new Date();
This produces something like "Sun May 02 21:49:02 GMT-05:00 1999". It's not pretty, but it is a quick way to display the time.
To format a date, use the
See the Java API documentation for a good description of this class.
The Calendar class can be used