Core JAVAWrite Once, Run Anywhere |
Java provides the Date class available in java.util package, this class encapsulates the current date and time.
The Date class supports two constructors. The first constructor initializes the object with the current date and time.
The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970
Once you have a Date object available, you can call any of the following support methods to play with dates:
|
Getting Current Date & Time
This is very easy to get current date and time in Java. You can use a simple Date object with toString()method to print current date and time as follows:
Output
Date Comparison
There are following three ways to compare two dates:
Date Formatting using SimpleDateFormat
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
Example
Output
Simple DateFormat format codes
To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:
|
Date Formatting using printf
Date and time formatting can be done very easily using printf method. You use a two-letter format, starting with t and ending in one of the letters of the table given below.
Example
Output
It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted.
The index must immediately follow the %, and it must be terminated by a $.
Example
Output
Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again.
Example
Output
Date and Time Conversion Characters
|
There are other useful classes related to Date and time. For more detail you can refer to Java Standard documentation.
Parsing Strings into Dates
The SimpleDateFormat class has some additional methods, notably parse( ) , which tries to parse a string according to the format stored in the given SimpleDateFormat object.
Example
Output
Sleeping for a While
You can sleep for any period of time from one millisecond up to the lifetime of your computer. For example, following program would sleep for 10 seconds:
Example
Output
Measuring Elapsed Time
Sometime you may need to measure point in time in milliseconds. So let's re-write above example once again:
Example
Output