- 在jdk1.7的時(shí)候过蹂,我們使用日期十绑,一般都是使用,java.util.Date酷勺,到了jdk8之后本橙,現(xiàn)在官方已經(jīng)建議我們使用新的時(shí)間類。在此把我實(shí)驗(yàn)的一些方法記錄一下脆诉。
- 首先我們先來看一下jdk8中的一些新時(shí)間類
Instant:表示時(shí)刻甚亭,不直接對(duì)應(yīng)年月日信息贷币,需要通過時(shí)區(qū)轉(zhuǎn)換
LocalDateTime: 表示與時(shí)區(qū)無關(guān)的日期和時(shí)間信息,不直接對(duì)應(yīng)時(shí)刻亏狰,需要通過時(shí)區(qū)轉(zhuǎn)換
LocalDate:表示與時(shí)區(qū)無關(guān)的日期役纹,與LocalDateTime相比,只有日期信息暇唾,沒有時(shí)間信息
LocalTime:表示與時(shí)區(qū)無關(guān)的時(shí)間促脉,與LocalDateTime相比,只有時(shí)間信息策州,沒有日期信息
ZonedDateTime: 表示特定時(shí)區(qū)的日期和時(shí)間
ZoneId/ZoneOffset:表示時(shí)區(qū)
1.字符串和LocalDateTimeg互轉(zhuǎn)
//字符串和LocalDateTime互轉(zhuǎn)
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.now();
String localTime = df.format(time);
LocalDateTime ldt = LocalDateTime.parse("2020-01-18 10:12:05",df);
System.out.println("LocalDateTime轉(zhuǎn)成String的時(shí)間:"+localTime);
System.out.println("String類型轉(zhuǎn)成LocalDateTime:"+ldt);
- 字符串和LocalDate互轉(zhuǎn)
//字符串和LocalDate互轉(zhuǎn)
DateTimeFormatter localDateFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
String localDateStr = localDateFormatter.format(localDate);
System.out.println("LocalDate轉(zhuǎn)字符串:" + localDateStr);
LocalDate strConvertLocalDate = LocalDate.parse("2019/11/11", localDateFormatter);
System.out.println(strConvertLocalDate);
3.與java.util.Date互轉(zhuǎn)
//Date轉(zhuǎn)LocalDateTime
Date date = new Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
System.out.println(localDateTime);
//LocalDateTime轉(zhuǎn)Date
LocalDateTime localDateTime2Date = LocalDateTime.now();
ZoneId zone2 = ZoneId.systemDefault();
Instant instant2 = localDateTime2Date.atZone(zone2).toInstant();
java.util.Date date2 = Date.from(instant2);
System.out.println(date2);
4.與LocalDate互轉(zhuǎn)
LocalDateTime now = LocalDateTime.now();
LocalDate localDateTimeToLocalDate = now.toLocalDate();
System.out.println(localDateTimeToLocalDate);
//LocalDate 轉(zhuǎn)LocalDateTime
LocalDate localDate3 = LocalDate.now();
ZoneId zone3 = ZoneId.systemDefault();
Instant instant3 = localDate3.atStartOfDay().atZone(zone3).toInstant();
java.util.Date date3 = Date.from(instant3);
System.out.println(date3);
5.時(shí)間比較
//不管是LocalDate還是LocalDateTime都提供了compileTo方法瘸味,可以很方便的進(jìn)行比較
//用一種比較古老的方式來比較,正好也使用一下LocalDateTime轉(zhuǎn)時(shí)間綴抽活。
LocalDateTime compileNow = LocalDateTime.now();
Long epochMilli = compileNow.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
LocalDateTime compileOther = LocalDateTime.parse("2019-11-11 00:00:00", df);
Long otherMill = compileOther.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
System.out.println(epochMilli - otherMill);