Java Reference
In-Depth Information
9/10/2011
7
2:45:57
Saturday
253
Days left in 2011: 112
37
How It Works
Many applications require the use of the current calendar date. It is often also necessary
to obtain the current time. There are different ways to do that, and the solution to this
recipe demonstrates three of them. The Date-Time API includes a LocalDateTime
class that enables you to capture the current date and time by invoking its now()
method. A specified date and time can be obtained by specifying the corresponding
int and Month type parameters when calling LocalDateTime.of() . There are
also a multitude of methods available for use via a LocalDateTime instance, such
as getHours(), getMinutes(), getNanos() and getSeconds() ,
which allow for finer-grained control of the date and time. An instance of
LocalDateTime also contains methods for performing calculations, conversions,
comparisons, and more. For brevity, all of the methods are not listed here, but for more
information, refer to the online documentation at http://docs.oracle.com/
javase/8/docs/api/java/time/LocalDateTime.html . Solution #1 to
this recipe demonstrates the use of the LocalDateTime , showcasing how to perform
calculations and obtain portions of the date and time for further use.
By default, the java.util.Date class can be instantiated with no arguments to
return the current date and time. The Date class can also be used to return the current
time of day via the getTime() method. As mentioned in the solution, the
getTime() method returns the number of milliseconds since January 1, 1970,
00:00:00 GMT, represented by the Date object that is in use. There are several other
methods that can be called against a Date object with regard to breaking down the
current date and time into more granular intervals. For instance, the Date class has the
methods getHours() , getMinutes() , getSeconds() , getMonth() ,
getDay() , getTimezoneOffset() , and getYear() . However, it is not advis-
able to use any of these methods, with the exception of getTime() , because each has
been deprecated by the use of the java.time.LocalDateTime and the
Search WWH ::




Custom Search