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.8K+ Learners
    4.58  (106)
    Python Tkinter
    1 hrs
    Beginner
    5.7K+ Learners
    4.56  (726)
    Database Normalization
    1 hrs
    Beginner
    5.8K+ Learners
    4.66  (678)
    Pattern Program in Java
    2 hrs
    Beginner
    3.6K+ Learners
    4.49  (85)
    DML Statements
    1 hrs
    Beginner
    4.8K+ Learners
    4.48  (501)
    GCD of Two Numbers
    2 hrs
    Beginner
    1.1K+ Learners
    4.65  (49)
    Language Translator in Python
    2 hrs
    Intermediate
    3.1K+ Learners
    4.69  (132)
    Matrix Multiplication in C
    1 hrs
    Beginner
    3.9K+ Learners
    4.45  (283)
    Waterfall Model
    1 hrs
    Beginner
    6.3K+ Learners
    4.48  (874)