Java Reference
In-Depth Information
In the Date-Time API, classes representing date, time, and datetime have a now() method that returns the current
date, time, or datetime, respectively. The following snippet of code creates date-time objects representing a date, a
time, and a combination of them with and without a time zone:
LocalDate dateOnly = LocalDate.now();
LocalTime timeOnly = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
ZonedDateTime dateTimeWithZone = ZonedDateTime.now();
A LocalDate is not time zone-aware. It will be interpreted differently in different time zones at the same moment
of time. A LocalDate object is used for storing a date value when the time and time zone are not important to give a
meaning to the date value, such as a birth date, the publication date of a book, etc.
You can specify the components of a datetime object using the static factory method of() . The following snippet
of code creates a LocalDate by specifying the year, month, and day components of a date:
// Create a LocalDate representing January 12, 1968
LocalDate myBirthDate = LocalDate.of(1968, JANUARY, 12);
a LocalDate stores a date-only value without a time and time zone. When you obtain a LocalDate using the
static method now() , the system default time zone is used to get the date value.
Tip
Listing 12-1 shows how to get the current date, time, datetime, and datetime with the time zone. It also shows
how to construct a date from year, month of year, and day of month. You may get a different output as it prints the
current values for date and time.
Listing 12-1. Obtaining Current Date, Time, and Datetime, and Constructing a Date
// CurrentDateTime.java
package com.jdojo.datetime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import static java.time.Month.JANUARY;
public class CurrentDateTime {
public static void main(String[] args) {
// Get current date, time, and datetime
LocalDate dateOnly = LocalDate.now();
LocalTime timeOnly = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
ZonedDateTime dateTimeWithZone = ZonedDateTime.now();
System.out.println("Current Date: " + dateOnly);
System.out.println("Current Time: " + timeOnly);
System.out.println("Current Date and Time: " + dateTime);
System.out.println("Current Date, Time, and Zone: " + dateTimeWithZone);
 
 
Search WWH ::




Custom Search