Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 07:30:11 Viewed : 573
In Java 8, the java.time
package provides a powerful and flexible set of classes for working with dates, times, and time zones. Here is an overview of using LocalDate
, LocalTime
, LocalDateTime
, and ZonedDateTime
with time zones in Java 8:
javaLocalDate localDate = LocalDate.now(); // Current date
javaLocalTime localTime = LocalTime.now(); // Current time
LocalDate
and LocalTime
.javaLocalDateTime localDateTime = LocalDateTime.now(); // Current date and time
LocalDateTime
.javaZoneId newYorkZone = ZoneId.of("America/New_York");
ZonedDateTime zonedDateTime = ZonedDateTime.now(newYorkZone); // Current date and time in New York
ZoneId
is used to represent time zones.ZoneId.getAvailableZoneIds()
.javaSet<String> availableZoneIds = ZoneId.getAvailableZoneIds();
javaimport java.time.*;
import java.util.Set;
public class DateTimeWithTimeZoneJava8Example {
public static void main(String[] args) {
// LocalDate
LocalDate localDate = LocalDate.now();
System.out.println("LocalDate: " + localDate);
// LocalTime
LocalTime localTime = LocalTime.now();
System.out.println("LocalTime: " + localTime);
// LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("LocalDateTime: " + localDateTime);
// ZonedDateTime
ZoneId newYorkZone = ZoneId.of("America/New_York");
ZonedDateTime zonedDateTime = ZonedDateTime.now(newYorkZone);
System.out.println("ZonedDateTime in New York: " + zonedDateTime);
// Available Time Zones
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
System.out.println("Available Time Zones: " + availableZoneIds);
// Working with Time Zones
ZoneId berlinZone = ZoneId.of("Europe/Berlin");
ZonedDateTime berlinDateTime = ZonedDateTime.now(berlinZone);
System.out.println("ZonedDateTime in Berlin: " + berlinDateTime);
}
}
In this Java 8 example, LocalDate
, LocalTime
, and LocalDateTime
are used to represent date and time without time zone information. The ZonedDateTime
class is used to represent date and time with a specific time zone. Additionally, the ZoneId
class is used to specify time zones, and ZoneId.getAvailableZoneIds()
provides a set of available time zone IDs.