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.51  (91)
    Python Tkinter
    1 hrs
    Beginner
    5.5K+ Learners
    4.55  (546)
    Database Normalization
    1 hrs
    Beginner
    5.6K+ Learners
    4.67  (636)
    Pattern Program in Java
    2 hrs
    Beginner
    3.6K+ Learners
    4.45  (71)
    DML Statements
    1 hrs
    Beginner
    4.7K+ Learners
    4.48  (475)
    GCD of Two Numbers
    2 hrs
    Beginner
    1.1K+ Learners
    4.64  (36)
    Language Translator in Python
    2 hrs
    Intermediate
    3K+ Learners
    4.66  (114)
    Matrix Multiplication in C
    1 hrs
    Beginner
    3.8K+ Learners
    4.45  (273)
    Waterfall Model
    1 hrs
    Beginner
    6.1K+ Learners
    4.49  (752)