Java 8 Date Time API
- schick09
- Jun 24, 2024
- 2 min read
Working with dates and times has never been particularly intuitive in Java - and usually the source of more than a few loud expletives. With Java 8 a new Date Time API was introduced. All of the classes are immutable - so they are safe for multi-threading.. This API also has classes for human-readable dates and times as well as Unix timestamps. . There are also operations to perform common functions like adding, subtracting, formatting, parsing and accessing separate date/time pieces and parts..
LocalDate
This is the Date in default format of yyy-MM-dd. The now() method will get you the current date. You can provide arguments for args for year, month, and day to create a LocalDate instance. You can also specify time zone.
LocalDate firstDay_2024 = LocalDate.of(2024, Month.JANUARY, 1);
LocalTime
This is the time in default format hh:mm:ss.zzz
LocalTime specificTime = LocalTime.of(12,20,25,40);
LocalDateTime
This is the date and time in default format yyyy-MM-dd-HH-mm-ss.zzz. There is a factory method that takes a LocalDate and LocalTime.
Instant
This stores the date and time as a unix timestamp
There are several utility operations available to add/subtract days, weeks, months. Here are several examples you can use
System.out.println("Year "+today.getYear()+" is Leap Year? "+today.isLeapYear());
//Compare two LocalDate for before and after
System.out.println("Today is before 01/01/2015? "+today.isBefore(LocalDate.of(2015,1,1)));
//Create LocalDateTime from LocalDate
System.out.println("Current Time="+today.atTime(LocalTime.now()));
//plus and minus operations
System.out.println("10 days after today will be "+today.plusDays(10));
System.out.println("3 weeks after today will be "+today.plusWeeks(3));
System.out.println("20 months after today will be "+today.plusMonths(20));
System.out.println("10 days before today will be "+today.minusDays(10));
System.out.println("3 weeks before today will be "+today.minusWeeks(3));
System.out.println("20 months before today will be "+today.minusMonths(20));
//Temporal adjusters for adjusting the dates
System.out.println("First date of this month= "+today.with(TemporalAdjusters.firstDayOfMonth()));
LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
System.out.println("Last date of this year= "+lastDayOfYear);
Period period = today.until(lastDayOfYear);
System.out.println("Period Format= "+period);
System.out.println("Months remaining in the year= "+period.getMonths());
There are also multiple date formatters and parsers. Here are a few examples you can use
//specific format
System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));

Comments