Java

Date & Time in Java

Date & Time in Java

In Java, the Date and Time API (java. time package) provides a rich set of classes for representing and manipulating date and time values. 
The most important classes in the Date and Time API are 
● LocalDate: represents a date (year, month, and day) without a time or time zone. 
● LocalTime: represents a time of day (hour, minute, and second) without a date or time zone. 
● LocalDateTime: represents a date and time without a time zone.
● ZonedDateTime: represents a date and time with a time zone. 
Ex : 

LocalDate date = LocalDate.of(2022, 3, 25); 

The above code creates a LocalDate object representing the date "2022-03-25" LocalTime time = LocalTime.of(12, 15, 30); 
The above code creates a LocalTime object representing the time "12:15:30" 
You can also create LocalDateTime and ZonedDateTime objects by combining date and time. For example, the following code creates a LocalDateTime object representing the date and time "2022-03-25T12:15:30": 

LocalDateTime dateTime = LocalDateTime.of(date, time); 

Java also provides a class called Instant, which represents a point in time in the format of a timestamp. Instant can be used to represent both the date and time values. 
Example: 

Instant instant = Instant.now(); 

Java also provides several classes for working with durations, such as Period and Duration. 
A period is used to represent a duration in terms of years, months, and days. Duration is used to represent a duration in terms of seconds and nanoseconds. 
Example: 

LocalDate start = LocalDate.of(2022, 3, 25); 
LocalDate end = LocalDate.of(2022, 5, 25); 
Period period = Period.between(start, end); 
long seconds = Duration.between(time1, time2).getSeconds(); 

Java also provides a way to format date and time values using the DateTimeFormatter class. This class provides a variety of predefined formatters, such as ISO_LOCAL_DATE, ISO_LOCAL_TIME, and ISO_LOCAL_DATE_TIME, as well as the ability to create custom formatters. 
 

Top course recommendations for you

    Graphs in Python
    1 hrs
    Beginner
    2.7K+ Learners
    4.5  (84)
    Python Tkinter
    1 hrs
    Beginner
    5.3K+ Learners
    4.54  (494)
    Database Normalization
    1 hrs
    Beginner
    5.4K+ Learners
    4.67  (546)
    Pattern Program in Java
    2 hrs
    Beginner
    3.5K+ Learners
    4.42  (64)
    DML Statements
    1 hrs
    Beginner
    4.6K+ Learners
    4.47  (450)
    GCD of Two Numbers
    2 hrs
    Beginner
    1.1K+ Learners
    4.62  (34)
    Language Translator in Python
    2 hrs
    Intermediate
    3K+ Learners
    4.64  (109)
    Matrix Multiplication in C
    1 hrs
    Beginner
    3.8K+ Learners
    4.45  (272)
    Waterfall Model
    1 hrs
    Beginner
    5.9K+ Learners
    4.47  (628)