读后笔记 -- Java核心技术(第11版 卷 II) Chapter6 日期和时间 API
6.1 TimeLine
1. A duration is the difference between two instants.
2. Measuring the running time of an algorithm:
Instant start = Instant.now(); runAlgorithm(); Instant end = Instant.now(); Duration timeElapsed = Duration.between(start, end); long mills = timeElapsed.toMillis();
3. Conversely, you can adjust an Instant by a Duration:
Instant start = Instant.now();
Instant later = start.plus(Duration.ofHours(8));
Note: Instant and Duration are immutable. This plus method returns a new Instant object.
4. Other methods for arithmetic and comparisions:
boolean overTenTimesFaster = timeElapsed.multipliedBy(10).minus(timeElapsed2).isNegative();
5. Usually simpler to work with nanoseconds:
boolean overTenTimesFaster = timeElapsed.toNanos() * 10 < timeElapsed.toNanos();
6.2 Local Dates
1. A LocalDate is a calendar date without a time zone.
2. Construct a LocalDate with one of the factory methods:
LocalDate today = LocalDate.now(); // Today's date LocalDate alonzosBirthday = LocalDate.of(1903, Month.JUNE, 14); // 指定日期
3. Methods plusDays, plusWeeks, plusMonths, plusYear (and minusXxx):
LocalDate programmersDay = LocalDate.of(2016, 1, 1).plusDays(255);
4. To find the number of days between two dates, call:
int days = independenceDay.until(christmas, ChronoUnit.DAYS); // 174 days
5. Caution: Calling plusMonths can yield implausible results.
- LocalDate.of(2016, 1, 31).plusMonths(1) yields February 29, 2016, not Jan 31
6. Instant 的时间长度是 duration,LocalDate 的本地日期长度是 Period
LocalDate end = LocalDate.of(2022, 1,31); System.out.println(end.plus(Period.ofMonths(1))); // 2022-02-28
Weekdays
1. The getDayOfWeek() yields the weekday of a LocalDate:
DayOfWeek weekday = LocalDate.of(1990, Month.JANUARY, 1).getDayOfWeek();
2. DayOfWeek.MONDAY has numerical value 1, and DayOfWeek.SUNDAY has value 7:
int value = weekday.getValue();
Note: the weekend comes at the end ! 和 java.tuil.Calendar 不同, 其 星期日的值是 1.
3. DayOfWeek can do arithmetic modulo 7:
- DayOfWeek.SATURDAY.plus(3) yields DayOfWeek.TUESDAY
6.3 Date Adjusters
1. For scheduling applications, you may need to compute dates such as "the first Tuesday of every month". The TemporalAdjusters class provides a number of static methods for common adjustments.
2. LocalDate
2.1 Compute the first Tuesday of a month:
LocalDate firstTuesday = LocalDate.of(year, month, 1).with(
TemporalAdjusters.nextOrSame(DayOfWeek.TUESDAY));
2.2 You can make your own adjusters:
TemporalAdjuster NEXT_WORKDAY = TemporalAdjusters.ofDateAdjuster(w -> { LocalDate result = w; do { result = result.plusDays(1); } while (result.getDayOfWeek().getValue() >= 6); return result; }); // call LocalDate firstWorkday = LocalDate.of(year, 1, 1).with(NEXT_WORKDAY);
6.4. LocalTime
1. A LocalTime represents a time of day, such as 22:30:00
2. Create an instance with a factory method:
LocalTime rightNow = LocalTime.now();
LocalTime bedTime = LocalTime.of(22, 30, 0);
3. There are methods to add hours, minutes, seconds, or nanoseconds:
LocalTime wakeup = bedtime.plusHours(8);
4. LocalTime doesn't concern itself with AM/PM - that is left to formatters.
5. There is also a LocalDateTime for a timezone-independent date and time.
6.5 ZonedTime
1. The ZonedDateTime class handles the messiness. Each time zone has an officially assigned ID.
ZonedID.getAvailableIds() // lists them all
2. Get a ZonedDateTime like this(也是有2个方法,同样的有:LocalDate, LocateTime):
ZonedDateTime now = ZonedDateTime.now(); ZonedDateTime apollo11launch = ZonedDateTime.of(1969,7,16,9,32,0,0, ZoneId.of("America/New_York")); // // 1969-07-16T09:32-04:00[America/New_York], -04:00: means it is 4 hours later than UTC
3. A ZonedDateTime is a specific point in time. Can convert to/from Instant:
Instant instant = apollo11launch.toInstant(); // 时区时间 -> Instant ZonedDateTime launchInUTC = instant.atZone(ZoneId.of("UTC")); // Instant -> 时区时间
4. Daylight Savings Time
4.1 Daylight savings time is more complicated than time zones.
4.2 Daylight savings time starts and ends at different times across the world.
4.3 The rules change over time. ZonedDateTime handles the rules, as published in the volunteer-maintained "tz database"
4.4 Beware of below things:
4.4.1 times that doesn't exist:
ZonedDateTime skipped = ZonedDateTime.of(LocalDate.of(2013, 3, 31), LocalTime.of(2, 30), ZoneId.of("Europe/Berlin")); // Constructs March 31 3:30 -- Central Europe switched to DST at 2:00, then 2:00~ 3:00 will disappear
4.4.2 Beware of adjusting a date across daylight savings time boundaries:
ZonedDateTime nextMeeting = meeting.plus(Duration.ofDays(7)); //Caution! Won't work with daylight savings time. It may lost time because of daylight savings time.
Instead, use the Period class:
ZonedDateTime nextMeeting = meeting.plus(Period.ofDays(7)); // OK
注:同 section 6.2 Duration 是时间长度, Period 是 日期长度
6.7 Legacy Date and Time Classes
1. java.util.Date -> Instant : Date.toInstant;
Instant -> java.util.Date: Date.from(Instant);