5.2 LocalDates
现在让我们从绝对时间转向人工时间,在新的API里有两种人工时间:local date/time 以及zoned time.
其中local date/time不包含时区信息。
比如1903年6月14(拉姆达表达式的发明者出生日),此种日期既不包含当天的时间,也不包含时区信息,所以它不能表示精确的时间点;相反,July 16, 1969, 09:32:00 EDT(中午)是一个时区时间,表示精确的时间点。
其实,有许多计算方式是不需要时区信息的,甚至在某些情况下,时区成为一种累赘。假设你在每周十点安排会议,如果你在最近的时区时间上增加7天,并且刚好跨国白昼时间分界线,会议要么早一小时,要么晚一小时。
由于以上原因,API设计者建议不要用时区时间,除非你想要表示绝对的时刻。生日,假日,日程时间等等通常最好用本地时间表示。
LocalDate包含年月日信息,你可以用以下方式来创建:
LocalDate today = LocalDate.now(); // Today’s date
LocalDate alonzosBirthday = LocalDate.of(1903, 6, 14);
alonzosBirthday = LocalDate.of(1903, Month.JUNE, 14);
不同于Java.util.Date中不规则的惯例(月份从0开始,年份从1900开始),你可以使用月份数,包括月份枚举。
下表展示了LocalDate对象最有用的方法。
Table 5–2 LocalDate Methods
Method Description
含义:These static methods construct a LocalDate, either from the
current time or from a given year, month, and day.
–方法名:
now, of
Adds a number of days, weeks, months, or years to this
LocalDate.
–方法名:
plusDays, plusWeeks,plusMonths, plusYears
Subtracts a number of days, weeks, months, or years from
this LocalDate.
–方法名:
minusDays, minusWeeks,minusMonths, minusYears
plus, minus Adds a Duration or Period.
Returns a new LocalDate with the day of month, day of year,
month, or year changed to the given value.
–方法名:
withDayOfMonth,withDayOfYear,withMonth, withYear
getDayOfMonth Gets the day of the month (between 1 and 31).
getDayOfYear Gets the day of the year (between 1 and 366).
Gets the day of the week, returning a value of the DayOfWeek
enumeration.
–方法名:
getDayOfWeek
Gets the month as a value of the Month enumeration, or as
a number between 1 and 12.
–方法名:
getMonth, getMonthValue
getYear Gets the year, between –999,999,999 and 999,999,999.
Gets the Period, or the number of the given ChronoUnits,
between two dates.
–方法名:
until
Compares this LocalDate with another.
–方法名:
isBefore, isAfter
Returns true if the year is a leap year—that is, if it is
divisible by 4 but not by 100, or divisible by 400. The
algorithm is applied for all past years, even though that is
historically inaccurate. (Leap years were invented in the
year –46, and the rules involving divisibility by 100 and
400 were introduced in the Gregorian calendar reform of
The reform took over 300 years to become universal.)
–方法名:
isLeapYear
比如:参数Day是一年中的第256天,你可以用以下方式运算:
LocalDate programmersDay = LocalDate.of(2014, 1, 1).plusDays(255);