Java Reference
In-Depth Information
In your application, you want to display not only the current date, but also the current
time.
Solution #1
Make use of the LocalDateTime class, which is part of the new Date-Time API, to
capture and display the current date and time. The LocalDateTime class contains a
method named now() , which can be used to obtain the current date and time together.
The following lines of code demonstrate how to do so:
LocalDateTime ldt = LocalDateTime.now();
System.out.println("Local Date and Time: " + ldt);
The resulting LocalDateTime object contains both the date and time, but no
time zone information. The LocalDateTime class also contains additional methods
that provide options for working with date-time data. For instance, to return a
LocalDateTime object with a specified date and time, pass parameters of int type
to the LocalDateTime.of() method, as follows:
// Obtain the LocalDateTime object of the date 11/11/2000
at 12:00
LocalDateTime ldt2 = LocalDateTime.of(2000,
Month.NOVEMBER, 11, 12, 00);
The following examples demonstrate a handful of the methods that are available in
a LocalDateTime object:
// Obtain the month from LocalDateTime object
Month month = ldt.getMonth();
int monthValue = ldt.getMonthValue();
System.out.println("Month: " + month);
System.out.println("Month Value: " + monthValue);
// Obtain day of Month, Week, and Year
int day = ldt.getDayOfMonth();
DayOfWeek dayWeek = ldt.getDayOfWeek();
int dayOfYr = ldt.getDayOfYear();
System.out.println("Day: " + day);
Search WWH ::




Custom Search