使用Java8,新的日期时间API解决了旧的日期时间API的以下问题、缺陷:
非线程安全: java.util.Date不是线程安全的,因此开发者必须在使用日期处理并发性问题。新的日期时间API是不可变的,并且没有setter方法。
设计不佳: 默认的开始日期从1900年,开始每月从1天从0开始,所以没有统一。不直接使用方法操作日期。新的API提供了这样操作实用方法。
困难的时区处理: 开发人员必须编写大量的代码来处理时区的问题。新的API设计开发保持特定领域设计。
示例代码1 : LocalDate
LocalDate date = LocalDate.now();
int year=date.getYear();
int month =date.getMonth().getValue();
int day = date.getDayOfMonth();
int week =date.getDayOfWeek().getValue();
System.out.println("年:"+year);
System.out.println("月:"+month);
System.out.println("日:"+day);
System.out.println("星期几:"+week);
System.out.println( date.toString());
示例代码2: LocalDateTime
LocalDateTime dateTime =LocalDateTime.now();
int year=dateTime.getYear();
int month =dateTime.getMonth().getValue();
int day = dateTime.getDayOfMonth();
int week =dateTime.getDayOfWeek().getValue();
int hour= dateTime.getHour();
int minute= dateTime.getMinute();
int second= dateTime.getSecond();
int nano= dateTime.getNano();
System.out.println("年:"+year);
System.out.println("月:"+month);
System.out.println("日:"+day);
System.out.println("星期几:"+week);
System.out.println("小时:"+hour);
System.out.println("分钟:"+minute);
System.out.println("秒:"+second);
System.out.println("纳秒:"+nano);
System.out.println(dateTime);
示例代码3: LocalTime
LocalTime time =LocalTime.now();
int hour =time.getHour();
int minute=time.getMinute();
int second=time.getSecond();
System.out.println("小时:"+hour);
System.out.println("分钟:"+minute);
System.out.println("秒:"+second);
示例代码4: 日期的加、减
LocalDate currentDate = LocalDate.now();
LocalDate newDate1= currentDate.plus(1,ChronoUnit.DAYS );//加1天
LocalDate newDate2= currentDate.plusDays(1);//加1天
LocalDate newDate3= currentDate.plus(-1,ChronoUnit.DAYS );//减1天
LocalDate newDate4= currentDate.minus(1,ChronoUnit.DAYS);//减1天
LocalDate newDate5= currentDate.minusDays(1);//减1天
System.out.println(currentDate);
System.out.println(newDate1);
System.out.println(newDate2);
System.out.println(newDate3);
System.out.println(newDate4);
System.out.println(newDate5);
示例代码5: 获取当前时间毫秒值
@Test
public void test1() {
Instant now = Instant.now();
System.out.println(now.getEpochSecond());//获取当前时间秒
System.out.println(now.toEpochMilli()); //获取当前时间毫秒值
}
示例代码6: 获取两个日期之间的间隔
/**
* 获取两个日期之间的间隔
*/
@Test
public void test9() {
LocalDate now1 = LocalDate.now();
LocalDate now2 = LocalDate.of(2018, 11, 1);
Period period= Period.between(now1, now2);
System.out.println(period.toString());//
System.out.println(period.getDays()); //当前日期距2018年11月1日相差几天
}
示例代码7: 时间的持续
@Test
public void testDuration(){
LocalTime time1 = LocalTime.now();
Duration twoHours = Duration.ofHours(2);
LocalTime time2 = time1.plus(twoHours);
Duration duration = Duration.between(time1, time2);
System.out.println("Duration: " + duration);
}