I've briefly summarized only the things that are likely to be used frequently in practice regarding the Java 8 date / time API.
LocalDate a = LocalDate.now();
System.out.println(a); // YYYY-MM-DD
LocalDate b = LocalDate.of(2017, 10, 17);
System.out.println(b); // 2017-10-17
LocalDate c = LocalDate.parse("2017-10-17");
System.out.println(c); // 2017-10-17
System.out.println(c.getYear()); // 2017
System.out.println(c.getMonthValue()); // 10
System.out.println(c.getDayOfMonth()); // 17
System.out.println(c.getDayOfWeek()); // "TUESDAY"
System.out.println(c.getDayOfWeek().getValue()); // 2
LocalDate d = c.plusDays(30);
System.out.println(c); // 2017-10-17 * Since it is immutable, the original value does not change.
System.out.println(d); // 2017-11-16
--Local Time is immutable --Handling time in 24 hours, no distinction between morning and afternoon
LocalTime a = LocalTime.of(0, 1, 2);
System.out.println(a); // 00:01:02
LocalTime b = a.plusHours(12);
System.out.println(a); // 00:01:02 * Since it is immutable, the original value does not change.
System.out.println(b); // 12:01:02
--Basic specifications are the same as LocalDate / LocalTime
--Use both LocalDate / LocalTime / LocalDateTime in the format
method
--The constant (formatter) defined in the DateTimeFormatter class can be used as an argument.
Formatter | Example |
---|---|
BASIC_ISO_DATE | 20171017 |
ISO_LOCAL_DATE | 2017-10-17 |
ISO_LOCAL_TIME | 10:15:30 |
LocalDateTime dateTime = LocalDateTime.of(2017, 10, 17, 10, 15, 30);
System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE)); // 20171017
System.out.println(dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE)); // 2017-10-17
System.out.println(dateTime.format(DateTimeFormatter.ISO_LOCAL_TIME)); // 10:15:30
--You can get the date difference and time difference.
LocalDateTime start = LocalDateTime.of(2017, 10, 17, 0, 0);
LocalDateTime end = LocalDateTime.of(2017, 11, 17, 0, 0);
Duration d = Duration.between(start, end);
System.out.println(d.toDays()); //The 31st)
System.out.println(d.toHours()); //744 (hours)
** (Reference & Caution) ** Java 8 also has an API called ** java.time.Period class ** to get the time period. However, this API asks for the period in the format of "○ years, ○ months, and ○ days". If you use it for the purpose of acquiring the so-called "days", it will be different from the expected result, so you must be careful not to misunderstand it.
LocalDate start = LocalDate.of(2017, 10, 17);
LocalDate end = LocalDate.of(2017, 11, 17);
Period p = Period.between(start, end);
System.out.println(p.getMonths()); //1 month
System.out.println(p.getDays()); //0th (Note) Bug if the expected result is assumed to be "31st"
Recommended Posts