Java 8 Date Time API
Clock为instant,date,time 提供时间,是包含时区的。
1 2 3 4 5 6
| Clock clock = Clock.systemDefaultZone(); long t0 = clock.millis(); Instant instant = clock.instant(); Date legacyDate = Date.from(instant);
|
java.time.Instant
Instant表示时间线上的一个点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| Instant now = Instant.now(); System.out.println(now.getEpochSecond()); Instant tomorrow = now.plus(1,ChronoUnit.DAYS); Instant tomorrow = now.plus(1,ChronoUnit.DAYS); System.out.println(now.compareTo(tomorrow)); System.out.println(now.isAfter(yesterday));
|
java.time.LocalDate
LocalDate保存日期部分,不包含时区,是不可变得类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| LocalDate today = LocalDate.now(); LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS); LocalDate yesterday = tomorrow.minusDays(2); LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4); DayOfWeek dayOfWeek = independenceDay.getDayOfWeek(); System.out.println(dayOfWeek); DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedDate(FormatStyle.MEDIUM) .withLocale(Locale.GERMAN); LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter); System.out.println(xmas);
|
java.time.LocalTime
LocalTime保存时间部分,不包含时区,是不可变得类。
1 2 3 4 5 6 7 8 9 10 11 12 13
| LocalTime now = LocalTime.now(); LocalTime late = LocalTime.of(23, 59, 59); System.out.println(late); DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedTime(FormatStyle.SHORT) .withLocale(Locale.GERMAN); LocalTime leetTime = LocalTime.parse("13:37", germanFormatter); System.out.println(leetTime);
|
java.time.LocalDateTime
LocalDateTime同时包括了时间和日期。不包含时区,是不可变得类。
1 2 3 4 5 6 7 8
| DateTimeFormatter formatter = DateTimeFormatter .ofPattern("MMM dd, yyyy - HH:mm"); LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter); String string = parsed.format(formatter); System.out.println(string);
|