Java8 新特性, Data與Time的正確使用姿勢

Java8自從發(fā)布到現(xiàn)在也有很長一段時(shí)間里俭正,新版本的java給我們帶來了很多激動(dòng)人心的新特性蕊唐,其中Date與Time的新API簡直給平時(shí)需要對時(shí)間日期的進(jìn)行各種復(fù)雜操作的同學(xué)帶來的新的福音,本文也主要從這一點(diǎn)出發(fā)來一起探索一下關(guān)于Data與Time的新特性

本文基本上以代碼為主,文字為輔琉闪。 不會出現(xiàn)過多的文字,因?yàn)榇蟛糠执a簡潔明了砸彬,一看變懂颠毙。

LocalDate

所有的關(guān)于 Data/Time 的新API都被收錄在 java.time package 中斯入,首先我們來看看 java.time.LocalDateLocalDate 表示了一個(gè)與時(shí)間無關(guān)的帶特定格式 year-month-day 的日期蛀蜜。

// the current date
LocalDate currentDate = LocalDate.now();
 
// 2014-02-10
LocalDate tenthFeb2014 = LocalDate.of(2017, Month.FEBRUARY, 10);
 
// months values start at 1 (2014-08-01)
LocalDate firstAug2014 = LocalDate.of(2014, 8, 1);
 
// the 65th day of 2010 (2010-03-06)
LocalDate sixtyFifthDayOf2010 = LocalDate.ofYearDay(2010, 65);

LocalTime, LocalDateTime

LocalTime是一個(gè)不帶日期的只關(guān)于時(shí)間的類刻两,LocalDateTime是LocalTime與LocalDate的結(jié)合體。下面是有關(guān)于這兩個(gè)類的用法:

LocalTime currentTime = LocalTime.now(); // current time
LocalTime midday = LocalTime.of(12, 0); // 12:00
LocalTime afterMidday = LocalTime.of(13, 30, 15); // 13:30:15
 
// 12345th second of day (03:25:45)
LocalTime fromSecondsOfDay = LocalTime.ofSecondOfDay(12345);
 
// dates with times, e.g. 2014-02-18 19:08:37.950
LocalDateTime currentDateTime = LocalDateTime.now();
 
// 2014-10-02 12:30
LocalDateTime secondAug2014 = LocalDateTime.of(2014, 10, 2, 12, 30);
 
// 2014-12-24 12:00
LocalDateTime christmas2014 = LocalDateTime.of(2014, Month.DECEMBER, 24, 12, 0);

通常情況下LocalDate/Time 會使用系統(tǒng)默認(rèn)的時(shí)鐘跟時(shí)區(qū)滴某,如果你想查詢其他時(shí)區(qū)的時(shí)間磅摹,可以用以下方法:

// current (local) time in Los Angeles
LocalTime currentTimeInLosAngeles = LocalTime.now(ZoneId.of("America/Los_Angeles"));

// current time in UTC time zone
LocalTime nowInUtc = LocalTime.now(Clock.systemUTC());

下面是一個(gè)綜合使用LocalTime/Date 的例子:

LocalDate date = LocalDate.of(2014, 2, 15); // 2014-02-15
 
boolean isBefore = LocalDate.now().isBefore(date); // false
 
// information about the month
Month february = date.getMonth(); // FEBRUARY
int februaryIntValue = february.getValue(); // 2
int minLength = february.minLength(); // 28
int maxLength = february.maxLength(); // 29
Month firstMonthOfQuarter = february.firstMonthOfQuarter(); // JANUARY
 
// information about the year
int year = date.getYear(); // 2014
int dayOfYear = date.getDayOfYear(); // 46
int lengthOfYear = date.lengthOfYear(); // 365
boolean isLeapYear = date.isLeapYear(); // false
 
DayOfWeek dayOfWeek = date.getDayOfWeek();
int dayOfWeekIntValue = dayOfWeek.getValue(); // 6
String dayOfWeekName = dayOfWeek.name(); // SATURDAY
 
int dayOfMonth = date.getDayOfMonth(); // 15
LocalDateTime startOfDay = date.atStartOfDay(); // 2014-02-15 00:00
 
// time information
LocalTime time = LocalTime.of(15, 30); // 15:30:00
int hour = time.getHour(); // 15
int second = time.getSecond(); // 0
int minute = time.getMinute(); // 30
int secondOfDay = time.toSecondOfDay(); // 55800

除此之外,新的api還提供一個(gè) Year 類霎奢, 下面我們來看看通過它我們能做些什么呢:

Year currentYear = Year.now();
Year twoThousand = Year.of(2000);
boolean isLeap = currentYear.isLeap(); // false
int length = currentYear.length(); // 365
 
// sixtyFourth day of 2014 (2014-03-05)
LocalDate date = Year.of(2014).atDay(64);

我們可以使用諸如 plus和minus 方法來對時(shí)間做一些基本的加減法户誓。這些方法會返回一個(gè)新的相關(guān)的實(shí)例:

LocalDate tomorrow = LocalDate.now().plusDays(1);
 
// before 5 houres and 30 minutes
LocalDateTime dateTime = LocalDateTime.now().minusHours(5).minusMinutes(30);

TemporalAdjusters 是另外一個(gè)非常重要的操作時(shí)間日期的接口,它提供了不同的靜態(tài)方法來提供對時(shí)間日期操作的支持:

LocalDate date = LocalDate.of(2014, Month.FEBRUARY, 25); // 2014-02-25
 
// first day of february 2014 (2014-02-01)
LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());
 
// last day of february 2014 (2014-02-28)
LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());

使用靜態(tài)導(dǎo)入會讓你的代碼更加具有可讀性

import static java.time.temporal.TemporalAdjusters.*;

...

// last day of 2014 (2014-12-31)
LocalDate lastDayOfYear = date.with(lastDayOfYear());

// first day of next month (2014-03-01)
LocalDate firstDayOfNextMonth = date.with(firstDayOfNextMonth());

// next sunday (2014-03-02)
LocalDate nextSunday = date.with(next(DayOfWeek.SUNDAY));

Time zones(時(shí)區(qū))

如果你想將 date/time 與時(shí)區(qū)聯(lián)系在一起的話幕侠,java提供了另外一個(gè)類 ZoneDateTIme 或者 OffsetDateTime

ZoneId losAngeles = ZoneId.of("America/Los_Angeles");
ZoneId berlin = ZoneId.of("Europe/Berlin");
 
// 2014-02-20 12:00
LocalDateTime dateTime = LocalDateTime.of(2014, 02, 20, 12, 0);
 
// 2014-02-20 12:00, Europe/Berlin (+01:00)
ZonedDateTime berlinDateTime = ZonedDateTime.of(dateTime, berlin);
 
// 2014-02-20 03:00, America/Los_Angeles (-08:00)
ZonedDateTime losAngelesDateTime = berlinDateTime.withZoneSameInstant(losAngeles);
 
int offsetInSeconds = losAngelesDateTime.getOffset().getTotalSeconds(); // -28800
 
// a collection of all available zones
Set<String> allZoneIds = ZoneId.getAvailableZoneIds();
 
// using offsets
LocalDateTime date = LocalDateTime.of(2013, Month.JULY, 20, 3, 30);
ZoneOffset offset = ZoneOffset.of("+05:00");
 
// 2013-07-20 03:30 +05:00
OffsetDateTime plusFive = OffsetDateTime.of(date, offset);
 
// 2013-07-19 20:30 -02:00
OffsetDateTime minusTwo = plusFive.withOffsetSameInstant(ZoneOffset.ofHours(-2));

TimeStamps 時(shí)間戳

LocalData 與ZonedDateTime 提供的時(shí)間日期方式都是人類可讀的帝美,但是如果我們需要從機(jī)器的角度來探索時(shí)間日期的話,我們可以使用這個(gè)類晤硕。即時(shí)計(jì)算從1970年1月1日(1970-01-01 00:00:00)的第一個(gè)秒開始的時(shí)間悼潭,也稱為EPOCH。 即時(shí)值可以是負(fù)數(shù)舞箍,如果它們在時(shí)代之前發(fā)生舰褪。 它們遵循ISO 8601表示日期和時(shí)間的標(biāo)準(zhǔn)。

// current time
Instant now = Instant.now();
 
// from unix timestamp, 2010-01-01 12:00:00
Instant fromUnixTimestamp = Instant.ofEpochSecond(1262347200);
 
// same time in millis
Instant fromEpochMilli = Instant.ofEpochMilli(1262347200000l);
 
// parsing from ISO 8601
Instant fromIso8601 = Instant.parse("2010-01-01T12:00:00Z");
 
// toString() returns ISO 8601 format, e.g. 2014-02-15T01:02:03Z
String toIso8601 = now.toString();
 
// as unix timestamp
long toUnixTimestamp = now.getEpochSecond();
 
// in millis
long toEpochMillis = now.toEpochMilli();
 
// plus/minus methods are available too
Instant nowPlusTenSeconds = now.plusSeconds(10);

Periods, Durations

這是另外兩個(gè)非常有用也很重要的類创译。Period主要使用基于date(日期)的值,例如 years, months, days 來代表一段時(shí)間抵知。Duration則是基于秒或者毫秒的。 他們的值可以是負(fù)數(shù)软族,如果結(jié)束時(shí)間發(fā)生在起始時(shí)間之前刷喜。

// periods
 
LocalDate firstDate = LocalDate.of(2010, 5, 17); // 2010-05-17
LocalDate secondDate = LocalDate.of(2015, 3, 7); // 2015-03-07
Period period = Period.between(firstDate, secondDate);
 
int days = period.getDays(); // 18
int months = period.getMonths(); // 9
int years = period.getYears(); // 4
boolean isNegative = period.isNegative(); // false
 
Period twoMonthsAndFiveDays = Period.ofMonths(2).plusDays(5);
LocalDate sixthOfJanuary = LocalDate.of(2014, 1, 6);
 
// add two months and five days to 2014-01-06, result is 2014-03-11
LocalDate eleventhOfMarch = sixthOfJanuary.plus(twoMonthsAndFiveDays);
 
 
// durations
 
Instant firstInstant= Instant.ofEpochSecond( 1294881180 ); // 2011-01-13 01:13
Instant secondInstant = Instant.ofEpochSecond(1294708260); // 2011-01-11 01:11
 
Duration between = Duration.between(firstInstant, secondInstant);
 
// negative because firstInstant is after secondInstant (-172920)
long seconds = between.getSeconds();
 
// get absolute result in minutes (2882)
long absoluteResult = between.abs().toMinutes();
 
// two hours in seconds (7200)
long twoHoursInSeconds = Duration.ofHours(2).getSeconds();

Formatting, Parsing

/ 2014-04-01 10:45
LocalDateTime dateTime = LocalDateTime.of(2014, Month.APRIL, 1, 10, 45);
 
// format as basic ISO date format (20140220)
String asBasicIsoDate = dateTime.format(DateTimeFormatter.BASIC_ISO_DATE);
 
// format as ISO week date (2014-W08-4)
String asIsoWeekDate = dateTime.format(DateTimeFormatter.ISO_WEEK_DATE);
 
// format ISO date time (2014-02-20T20:04:05.867)
String asIsoDateTime = dateTime.format(DateTimeFormatter.ISO_DATE_TIME);
 
// using a custom pattern (01/04/2014)
String asCustomPattern = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
 
// french date formatting (1. avril 2014)
String frenchDate = dateTime.format(DateTimeFormatter.ofPattern("d. MMMM yyyy", new Locale("fr")));
 
// using short german date/time formatting (01.04.14 10:45)
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
    .withLocale(new Locale("de"));
String germanDateTime = dateTime.format(formatter);
 
// parsing date strings
LocalDate fromIsoDate = LocalDate.parse("2014-01-20");
LocalDate fromIsoWeekDate = LocalDate.parse("2014-W14-2", DateTimeFormatter.ISO_WEEK_DATE);
LocalDate fromCustomPattern = LocalDate.parse("20.01.2014", DateTimeFormatter.ofPattern("dd.MM.yyyy"));

在不同的 date/time 對象之間的轉(zhuǎn)換

// LocalDate/LocalTime <-> LocalDateTime
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTimeFromDateAndTime = LocalDateTime.of(date, time);
LocalDate dateFromDateTime = LocalDateTime.now().toLocalDate();
LocalTime timeFromDateTime = LocalDateTime.now().toLocalTime();
 
// Instant <-> LocalDateTime
Instant instant = Instant.now();
LocalDateTime dateTimeFromInstant = LocalDateTime.ofInstant(instant, ZoneId.of("America/Los_Angeles"));
Instant instantFromDateTime = LocalDateTime.now().toInstant(ZoneOffset.ofHours(-2));
 
// convert old date/calendar/timezone classes
Instant instantFromDate = new Date().toInstant();
Instant instantFromCalendar = Calendar.getInstance().toInstant();
ZoneId zoneId = TimeZone.getDefault().toZoneId();
ZonedDateTime zonedDateTimeFromGregorianCalendar = new GregorianCalendar().toZonedDateTime();
 
// convert to old classes
Date dateFromInstant = Date.from(Instant.now());
TimeZone timeZone = TimeZone.getTimeZone(ZoneId.of("America/Los_Angeles"));
GregorianCalendar gregorianCalendar = GregorianCalendar.from(ZonedDateTime.now());

現(xiàn)在來看, 對于時(shí)間跟日期的操作真的是比以往方便了很多立砸,我們可以徹底告別各種蛋疼的邏輯操作了掖疮。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市颗祝,隨后出現(xiàn)的幾起案子浊闪,更是在濱河造成了極大的恐慌,老刑警劉巖螺戳,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件搁宾,死亡現(xiàn)場離奇詭異,居然都是意外死亡倔幼,警方通過查閱死者的電腦和手機(jī)盖腿,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人翩腐,你說我怎么就攤上這事鸟款。” “怎么了茂卦?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵何什,是天一觀的道長。 經(jīng)常有香客問我等龙,道長处渣,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任而咆,我火速辦了婚禮霍比,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘暴备。我一直安慰自己悠瞬,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布涯捻。 她就那樣靜靜地躺著浅妆,像睡著了一般。 火紅的嫁衣襯著肌膚如雪障癌。 梳的紋絲不亂的頭發(fā)上凌外,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天,我揣著相機(jī)與錄音涛浙,去河邊找鬼康辑。 笑死,一個(gè)胖子當(dāng)著我的面吹牛轿亮,可吹牛的內(nèi)容都是我干的疮薇。 我是一名探鬼主播,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼我注,長吁一口氣:“原來是場噩夢啊……” “哼按咒!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起但骨,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤励七,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后奔缠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體掠抬,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年校哎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了两波。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,030評論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖雨女,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情阳准,我是刑警寧澤氛堕,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站野蝇,受9級特大地震影響讼稚,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜绕沈,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一锐想、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧乍狐,春花似錦赠摇、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至惜傲,卻和暖如春洽故,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背盗誊。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工时甚, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人哈踱。 一個(gè)月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓荒适,卻偏偏與公主長得像,于是被迫代替她去往敵國和親嚣鄙。 傳聞我的和親對象是個(gè)殘疾皇子吻贿,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容