Java LocalDateTime
LocalDateTime
LocalDateTime is similar with ZonedDateTime, but it doesn’t have Zone idea.
LocalDateTime is just local time on the machine.
To provide service, date and time is critical problem.
LocalDateTime is for only local server provide date and time.
If you need to consider timezone, please use ZonedDateTime.
Example
LocalDateTime now = LocalDateTime.now(); // SG time System.out.println(now); ZonedDateTime znow = now.atZone(ZoneId.of("Asia/Tokyo")); System.out.println(znow); // Tokyo
Operations are similar with ZonedDateTime.
We can get year, month, day.
We can set them.
Calculate minus and plus.
LocalDateTime now = LocalDateTime.now(); System.out.println("Year :" + now.getYear()); System.out.println("Month Object:" + now.getMonth()); System.out.println("Month Value :" + now.getMonthValue()); System.out.println("Day :" + now.getDayOfMonth()); LocalDateTime firstDayOfMonth = now.withDayOfMonth(1); System.out.println("FirstDay :" + firstDayOfMonth); // Yesterday LocalDateTime yesterday = now.minusDays(1); System.out.println("Yesterday :" + yesterday); // Tomorrow LocalDateTime tomorrow = now.plusDays(1); System.out.println("Tomorrow :" + tomorrow);
Diff
LocalDateTime now = LocalDateTime.now(); LocalDateTime yesterday = now.minusDays(1); long days = yesterday.until(now, ChronoUnit.DAYS); System.out.println("Diff:" + days);