JavaSE8-The New Date and Time API(2)

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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章