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.3K+ Learners
    4.43  (56)
    Trees in Python
    2 hrs
    Beginner
    2.1K+ Learners
    4.64  (44)
    Python Tkinter
    1 hrs
    Beginner
    4.2K+ Learners
    4.55  (279)
    Database Normalization
    1 hrs
    Beginner
    4K+ Learners
    4.6  (213)
    Pattern Program in Java
    2 hrs
    Beginner
    3K+ Learners
    4.51  (49)
    DML Statements
    1 hrs
    Beginner
    3.7K+ Learners
    4.53  (244)
    GCD of Two Numbers
    2 hrs
    Beginner
    979 Learners
    4.63  (30)
    Language Translator in Python
    2 hrs
    Intermediate
    2.4K+ Learners
    4.66  (65)
    Matrix Multiplication in C
    1 hrs
    Beginner
    3.3K+ Learners
    4.47  (132)
    Waterfall Model
    1 hrs
    Beginner
    4.7K+ Learners
    4.46  (335)