新增日期时间类介绍:
新的时间及日期API位于java.time中,Java.time包中的是类是不可变且线程安全的。
Instant:
Instant类是用在机器可读的时间格式上的,它以Unix时间戳的形式存储日期
public static void main(String[] args) {
//当前时间戳2019-01-16T06:02:35.081Z
Instant now = Instant.now();
System.out.println("current timestamp is ..." + now);
//转换毫秒数
long l = now.toEpochMilli();
System.out.println("milli is ..." + l);
//时间戳转换
Instant instant = Instant.ofEpochMilli(now.toEpochMilli());
System.out.println("change timestamp is ..." + instant);
Duration duration = Duration.ofDays(30);
System.out.println("duration is ..." + duration);
}
LocalDate:
表示的是不带时间的日期。
public static void main(String[] args) {
//当前日期
LocalDate localDate = LocalDate.now();
System.out.println(localDate);
//设置时间为2019-01-16
LocalDate today = LocalDate.of(2019, Month.JANUARY, 16);
System.out.println("today is ...." + today);
//获取Asia时区下的当前日期
LocalDate kolkata = LocalDate.now(ZoneId.of("Asia/Kolkata"));
System.out.println("Asia/Kolkata today is ..." + kolkata);
//获取初始日期
LocalDate dateFromBase = LocalDate.ofEpochDay(365);
System.out.println("365 date from base is ..." + dateFromBase);
//设置某年下某天的日期
LocalDate yearDay = LocalDate.ofYearDay(2019, 16);
System.out.println("2019 year day 16 is ..." + yearDay);
}
LocalTime:
表示的是不带日期的时间。
public static void main(String[] args) {
//当前时间
LocalTime currentTime = LocalTime.now();
System.out.println("currentTime is ..." + currentTime);
//设置时间为13:45:59
LocalTime ofTime = LocalTime.of(13, 45, 59);
System.out.println("of time is ..." + ofTime);
//获取初始时间01/01/1970
LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000);
System.out.println("10000th second time= "+specificSecondTime);
}
LocalDateTime:
包含了时间与日期,不过没有带时区的偏移量。
public static void main(String[] args) {
//获取当前日期时间
LocalDateTime nowTime = LocalDateTime.now();
System.out.println("now ..." + nowTime);
nowTime = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println("now ..." + nowTime);
//设置时间为2019-01-16T13:53:59.000000233
LocalDateTime ofDateTime = LocalDateTime.of(2019, Month.JANUARY, 16, 13, 53, 59, 233);
System.out.println("of date time is ..." + ofDateTime);
}
加/减天数、周数、月份数:
public static void main(String[] args) {
LocalDate now = LocalDate.now();
//判断是否闰年
System.out.println("now year " + now.getYear() + " is leap year ?" +
now.isLeapYear() );
//比较两个日期先后
System.out.println("Today is before 2019-02-01?
"+now.isBefore(LocalDate.of(2019,2,1)));
//日期添加时间
System.out.println("Current Time="+now.atTime(LocalTime.now()));
//日期操作
System.out.println("now add 7day is .. "+now.plusDays(10));
System.out.println("now deAdd 7day is..." + now.plusWeeks(-1));
System.out.println("now deAdd 1year is..." + now.plusYears(-1));
//本月第一天
System.out.println("First date of this month =
"+now.with(TemporalAdjusters.firstDayOfMonth()));
//本年度最后一天
LocalDate lastDayOfYear = now.with(TemporalAdjusters.lastDayOfYear());
System.out.println("Last date of this year = "+lastDayOfYear);
}
Duration、Period :
Duration - 处理有关基于时间的时间量。
Period - 处理有关基于时间的日期数量。