java8新特性(6)— 日期与时间
全新的日期与时间处理
package com.common.jdk8;
import java.time.*;
public class Jdk8Test6 {
public static void main(String args[]){
Jdk8Test6 jdk8Test6 = new Jdk8Test6();
jdk8Test6.testLocalDateTime();
jdk8Test6.testZonedDateTime();
}
public void testLocalDateTime(){
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间: " + currentTime);
LocalDate date1 = currentTime.toLocalDate();
System.out.println("date1: " + date1);
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
System.out.println("月: " + month +", 日: " + day +", 秒: " + seconds);
LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);
System.out.println("date2: " + date2);
LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12);
System.out.println("date3: " + date3);
LocalTime date4 = LocalTime.of(22, 15);
System.out.println("date4: " + date4);
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("date5: " + date5);
}
public void testZonedDateTime(){
ZonedDateTime date1 = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");
System.out.println("date1: " + date1);
ZoneId id = ZoneId.of("Europe/Paris");
System.out.println("ZoneId: " + id);
ZoneId currentZone = ZoneId.systemDefault();
System.out.println("当期时区: " + currentZone);
}
}
运行结果
当前时间: 2019-07-02T01:25:17.250
date1: 2019-07-02
月: JULY, 日: 2, 秒: 17
date2: 2012-07-10T01:25:17.250
date3: 2014-12-12
date4: 22:15
date5: 20:15:30
date1: 2015-12-03T10:15:30+08:00[Asia/Shanghai]
ZoneId: Europe/Paris
当期时区: Asia/Shanghai