Java: Various time
classes
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.
Time in milliseconds since January 1, 1970
If you aren't familiar with Unix, this may sound a little strange, but it is the
common Unix way of measuring time and it has be adopted by Java. If you're just
measuring elapsed time, you can call System.currentTimeMillis(),
which avoids the overhead of creating a Calendar object. This returns a
long integer 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.
Getting a printable date and time
Simple, but ugly
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.
Formatting the date
To format a date, use the java.text.SimpleDateFormat class. See
the Java API documentation for a good description of this class.
Using the java.util.Calendar class
The Calendar class can be used to get the current date and time, represent
dates and times for the past or future, do date arithmetic, determine the hour,
day of the week, year, etc. This, as well as java.util.Date are the
common classes to use.
Calendar today = new GregorianCalendar(); // Current date and time.
Because Calendar is an abstract class, you must create a specific kind of
calendar to assign to it. The only supported subclass is
java.util.GregorianCalendar, which is the calendar that is commonly used
Using a Timer
You can use a javax.swing.Timer object to call a method of yours at regular
intervals. This is useful for many things, including animation. The Timer class
is easy to use - it calls its action listeners at specified intervals.
5 comments | | Score: 0
|