๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

New Date/Time API  


Introduction
  • Before Java 8, date and time handling was done using classes (Date, Calendar etc) from the java.util package.
  • However, the old Date-Time API had several disadvantages:
    • Mutability: Date and Calendar classes are mutable, making them not thread-safe.
    • Poor API Design: Month index starts from 0 (January), which is confusing for developers.
    • Limited Functionality: Lacks built-in support for time zones and formatting/parsing operations were cumbersome.
    • Complexity: Calendar and GregorianCalendar are verbose and difficult to use for simple tasks.
  • To overcome these problems, Java 8 introduced the New Date and Time API in the java.time package, which is immutable, thread-safe and much easier to use.

New Date API:
  • Java 8 introduced a new Date API with the java.time.LocalDate class to represent dates in a simple, clean and immutable way.
  • It handles year, month and day without time and timezone, making it ideal for working with pure dates like birthdays, holidays, and schedules.
  • Some important date-related classes present in new API are as follows:
    S.No Class / Interface Important Methods Purpose / Description
    1 LocalDate now(), of(), plusDays(), minusDays(), getDayOfWeek(), isLeapYear() Represents a date (year, month, day) without time and timezone.
    2 LocalDateTime now(), of(), plusHours(), minusMinutes(), toLocalDate(), toLocalTime() Represents a date + time (year, month, day, hour, minute, second) without timezone.
    3 ZonedDateTime now(), of(), withZoneSameInstant(), getZone(), toLocalDateTime() Represents a date + time with a specific timezone.
    4 OffsetDateTime now(), of(), getOffset(), withOffsetSameInstant(), toLocalDateTime() Represents date and time with an offset from UTC but not full time zone rules.
    5 Year now(), of(), isLeap(), plusYears(), minusYears() Represents a specific year.
    6 YearMonth now(), of(), lengthOfMonth(), isLeapYear(), plusMonths() Represents a year and month without a day.
    7 MonthDay now(), of(), isValidYear(), atYear() Represents a combination of month and day, without year.
  • Program 1:
    import java.time.*;
    
    public class MainApp1
    {
        public static void main(String[] args)
        {
            // 1. LocalDate
            LocalDate today = LocalDate.now();
            LocalDate specificDate = LocalDate.of(2025, 9, 19);
            LocalDate nextWeek = today.plusDays(7);
            LocalDate lastWeek = today.minusDays(7);
            DayOfWeek dayOfWeek = today.getDayOfWeek();
            boolean isLeap = today.isLeapYear();
    
            System.out.println("------ LocalDate ------");
            System.out.println("Today: " + today);
            System.out.println("Specific Date: " + specificDate);
            System.out.println("Next Week: " + nextWeek);
            System.out.println("Last Week: " + lastWeek);
            System.out.println("Day of Week: " + dayOfWeek);
            System.out.println("Is Leap Year: " + isLeap);
            System.out.println();
    
            // 2. LocalDateTime
            LocalDateTime currentDateTime = LocalDateTime.now();
            LocalDateTime specificDateTime = LocalDateTime.of(2025, 9, 19, 10, 30, 45);
            LocalDateTime plusHours = currentDateTime.plusHours(5);
            LocalDateTime minusMinutes = currentDateTime.minusMinutes(15);
    
            System.out.println("------ LocalDateTime ------");
            System.out.println("Current DateTime: " + currentDateTime);
            System.out.println("Specific DateTime: " + specificDateTime);
            System.out.println("Plus 5 Hours: " + plusHours);
            System.out.println("Minus 15 Minutes: " + minusMinutes);
            System.out.println("To LocalDate: " + currentDateTime.toLocalDate());
            System.out.println("To LocalTime: " + currentDateTime.toLocalTime());
            System.out.println();
    
            // 3. ZonedDateTime
            ZonedDateTime zonedNow = ZonedDateTime.now();
            ZonedDateTime specificZoned = ZonedDateTime.of(2025, 9, 19, 10, 30, 0, 0, ZoneId.of("Asia/Kolkata"));
            ZonedDateTime convertedZone = zonedNow.withZoneSameInstant(ZoneId.of("Europe/London"));
    
            System.out.println("------ ZonedDateTime ------");
            System.out.println("Current ZonedDateTime: " + zonedNow);
            System.out.println("Specific ZonedDateTime: " + specificZoned);
            System.out.println("Converted to London Zone: " + convertedZone);
            System.out.println("Zone: " + zonedNow.getZone());
            System.out.println("To LocalDateTime: " + zonedNow.toLocalDateTime());
            System.out.println();
    
            // 4. OffsetDateTime
            OffsetDateTime offsetNow = OffsetDateTime.now();
            OffsetDateTime specificOffset = OffsetDateTime.of(2025, 9, 19, 10, 30, 0, 0, ZoneOffset.ofHours(5));
            OffsetDateTime newOffset = offsetNow.withOffsetSameInstant(ZoneOffset.ofHours(2));
    
            System.out.println("------ OffsetDateTime ------");
            System.out.println("Current OffsetDateTime: " + offsetNow);
            System.out.println("Specific OffsetDateTime: " + specificOffset);
            System.out.println("Offset: " + offsetNow.getOffset());
            System.out.println("Converted Offset: " + newOffset);
            System.out.println("To LocalDateTime: " + offsetNow.toLocalDateTime());
            System.out.println();
        }
    }
  • Program 2:
    import java.time.*;
    
    public class MainApp2
    {
        public static void main(String[] args)
        {
            // 5. Year
            Year thisYear = Year.now();
            Year specificYear = Year.of(2028);
            boolean leap = specificYear.isLeap();
            Year nextYear = thisYear.plusYears(1);
            Year lastYear = thisYear.minusYears(1);
    
            System.out.println("------ Year ------");
            System.out.println("This Year: " + thisYear);
            System.out.println("Specific Year: " + specificYear);
            System.out.println("Is Leap Year: " + leap);
            System.out.println("Next Year: " + nextYear);
            System.out.println("Last Year: " + lastYear);
            System.out.println();
    
            // 6. YearMonth
            YearMonth currentMonth = YearMonth.now();
            YearMonth specificMonth = YearMonth.of(2025, 12);
            int lengthOfMonth = specificMonth.lengthOfMonth();
            boolean isLeapMonthYear = specificMonth.isLeapYear();
            YearMonth nextMonth = currentMonth.plusMonths(1);
    
            System.out.println("------ YearMonth ------");
            System.out.println("Current YearMonth: " + currentMonth);
            System.out.println("Specific YearMonth: " + specificMonth);
            System.out.println("Length of Month: " + lengthOfMonth);
            System.out.println("Is Leap Year: " + isLeapMonthYear);
            System.out.println("Next Month: " + nextMonth);
            System.out.println();
    
            // 7. MonthDay
            MonthDay todayMonthDay = MonthDay.now();
            MonthDay specificMonthDay = MonthDay.of(12, 25);
            boolean validForYear = specificMonthDay.isValidYear(2025);
            LocalDate dateFromMonthDay = specificMonthDay.atYear(2025);
    
            System.out.println("------ MonthDay ------");
            System.out.println("Today MonthDay: " + todayMonthDay);
            System.out.println("Specific MonthDay: " + specificMonthDay);
            System.out.println("Is Valid for 2025: " + validForYear);
            System.out.println("Converted to LocalDate: " + dateFromMonthDay);
        }
    }

New Time API:
  • Java 8 introduced a new Time API with the java.time.LocalTime class to represent time in a simple, clean, and immutable way.
  • It handles hour, minute, second and nanosecond without date and timezone, making it ideal for working with pure times like meeting times, alarms, and schedules.
  • Some important time-related classes present in new API are as follows:
    S.No Class / Interface Important Methods Purpose / Description
    1 LocalTime now(), of(), plusHours(), minusMinutes(), getHour(), getMinute() Represents a time (hour, minute, second, nanosecond) without date and timezone.
    2 OffsetTime now(), of(), getOffset(), withOffsetSameInstant(), toLocalTime() Represents time with an offset from UTC, but not full time zone rules.
    3 Duration between(), ofHours(), ofMinutes(), toHours(), toMinutes() Represents a time-based amount of time, such as seconds, minutes, or hours.
    4 Instant now(), ofEpochSecond(), plusSeconds(), minusMillis() Represents a moment on the timeline in UTC, useful for timestamps.
    5 ChronoUnit between(), plus(), minus() Used to measure amounts of time in units like hours, minutes, seconds, etc.
  • Program 1:
    import java.time.*;
    import java.time.temporal.ChronoUnit;
    
    public class MainApp3
    {
        public static void main(String[] args)
        {
            // 1. LocalTime
            LocalTime nowTime = LocalTime.now();
            LocalTime specificTime = LocalTime.of(14, 30, 45);
            LocalTime plusHours = nowTime.plusHours(2);
            LocalTime minusMinutes = nowTime.minusMinutes(15);
    
            System.out.println("------ LocalTime ------");
            System.out.println("Current Time: " + nowTime);
            System.out.println("Specific Time: " + specificTime);
            System.out.println("Plus 2 Hours: " + plusHours);
            System.out.println("Minus 15 Minutes: " + minusMinutes);
            System.out.println("Hour: " + nowTime.getHour());
            System.out.println("Minute: " + nowTime.getMinute());
            System.out.println();
    
            // 2. OffsetTime
            OffsetTime offsetNow = OffsetTime.now();
            OffsetTime specificOffset = OffsetTime.of(14, 30, 0, 0, ZoneOffset.ofHours(5));
            OffsetTime newOffset = offsetNow.withOffsetSameInstant(ZoneOffset.ofHours(2));
    
            System.out.println("------ OffsetTime ------");
            System.out.println("Current OffsetTime: " + offsetNow);
            System.out.println("Specific OffsetTime: " + specificOffset);
            System.out.println("Converted Offset: " + newOffset);
            System.out.println("Offset: " + offsetNow.getOffset());
            System.out.println("To LocalTime: " + offsetNow.toLocalTime());
            System.out.println();
    
            // 3. Duration
            LocalTime start = LocalTime.of(9, 0);
            LocalTime end = LocalTime.of(17, 30);
            Duration duration = Duration.between(start, end);
            Duration plusDuration = duration.plusHours(1);
    
            System.out.println("------ Duration ------");
            System.out.println("Duration between 9:00 and 17:30: " + duration.toHours() + " hours");
            System.out.println("Duration plus 1 hour: " + plusDuration.toHours() + " hours");
            System.out.println();
    
            // 4. Instant
            Instant instantNow = Instant.now();
            Instant instantLater = instantNow.plusSeconds(3600);
    
            System.out.println("------ Instant ------");
            System.out.println("Current Instant: " + instantNow);
            System.out.println("Instant after 1 hour: " + instantLater);
            System.out.println();
    
            // 5. ChronoUnit
            long minutesBetween = ChronoUnit.MINUTES.between(start, end);
            long hoursBetween = ChronoUnit.HOURS.between(start, end);
    
            System.out.println("------ ChronoUnit ------");
            System.out.println("Minutes between 9:00 and 17:30: " + minutesBetween);
            System.out.println("Hours between 9:00 and 17:30: " + hoursBetween);
        }
    }