Java8新时间与日期API—本地时间与时间戳

时间:2022-01-06 22:08:34
LocalDate/LocalTime/LocalDateTime类的实例是不可变的对象。

分别表示使用ISO-8691日历系统的日期、时间、日期和时间。它们提供了简单的日期或时间,并不包含当前的时间信息。也不包括与时区相关的信息。

package com.expgiga.Java8;

import java.time.*;

/**
*
*/
public class TestLocalDateTime {
public static void main(String[] args) {

//1.LocalDate LocalTime LocalDateTime使用的方式是一样的。
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);

LocalDateTime ldt2 = LocalDateTime.of(2017,10,10,11,22,33);
System.out.println(ldt2);

LocalDateTime ldt3 = ldt.plusYears(2);
System.out.println(ldt3);

LocalDateTime ldt4 = ldt.minusMonths(2);
System.out.println(ldt4);

System.out.println(ldt.getYear());
System.out.println(ldt.getMonthValue());
System.out.println(ldt.getDayOfMonth());
System.out.println(ldt.getHour());
System.out.println(ldt.getMinute());
System.out.println(ldt.getSecond());

//2.Instant:时间戳(以Unix元年:197011 00:00:00到某个时间之间的毫秒值)
Instant ins = Instant.now(); //默认获取的是UTC时区
System.out.println(ins);
System.out.println(ins.toEpochMilli()); //ms

Instant ins2 = Instant.ofEpochMilli(60);//60s
System.out.println(ins2);

OffsetDateTime odt = ins.atOffset(ZoneOffset.ofHours(8));
System.out.println(odt);

//3.
//Duration:计算两个"时间"之间的间隔
//Period:计算两个"日期"之间的间隔
Instant ins3 = Instant.now();
Instant ins4 = Instant.now();
Duration duration = Duration.between(ins3, ins4);
System.out.println(duration.toMillis());

LocalTime lt1 = LocalTime.now();
LocalTime lt2 = LocalTime.now();
System.out.println(Duration.between(lt1, lt2).toMillis());

LocalDate ld1 = LocalDate.now();
LocalDate ld2 = LocalDate.of(2015,1,1);
System.out.println(Period.between(ld1, ld2));
System.out.println(Period.between(ld1, ld2).getYears());
System.out.println(Period.between(ld1, ld2).getDays());
System.out.println(Period.between(ld1, ld2).getMonths());


}
}