欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java8 时间类常用方法

程序员文章站 2024-03-12 21:58:26
...
//当前日期
LocalDate date = LocalDate.now();//2020-07-12

//年月日
int year = date.getYear();//2020
int month = date.getMonthValue();//7
int day = date.getDayOfMonth();//12

//指定日期
LocalDate newDate = LocalDate.of(2019, 1, 1);//2019-01-0.1

//日期计算
date.plus(1, ChronoUnit.DAYS);
date.minus(1,ChronoUnit.DAYS);

//当前时间
LocalTime time = LocalTime.now();//23:25:38.100

//时间计算
time.plus(1,ChronoUnit.HOURS);
time.minus(1,ChronoUnit.HOURS);

//当前时间戳
Instant instant = Instant.now();//2020-07-12T15:25:38.101Z

//当前日期时间
LocalDateTime now = LocalDateTime.now();//2020-07-12T23:25:38.114

//字符串转化为日期
String dateStr = "20200712";
LocalDate dateParse = LocalDate.parse(dateStr, DateTimeFormatter.BASIC_ISO_DATE);//2020-07-12

//日期比较
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1,ChronoUnit.DAYS);
LocalDate yesterday = today.minus(1,ChronoUnit.DAYS);
System.out.println(today.isBefore(tomorrow));//true
System.out.println(today.isAfter(yesterday));//true

//日期转化为字符串
String dayStr = date.format(DateTimeFormatter.BASIC_ISO_DATE);

//按照指定格式格式化
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateString = "2020-07-12 22:17:09";

LocalDateTime dateParse2 = LocalDateTime.parse(dateString,dtf);//2020-07-12T22:17:09
String formatStr = now.format(dtf);//2020-07-12 23:25:38

//判断是不是闰年
date.isLeapYear();//true

//计算两个日期间的年数、月数、天数
LocalDate one = LocalDate.of(2019,1,1);
LocalDate two = LocalDate.now();
Period period = Period.between(one, two);
int years = period.getYears();//1年
int months = period.getMonths();//6个月
int days = period.getDays();//11天
//实际计算相隔天数
long result = two.toEpochDay()-one.toEpochDay();//558天

//时区设置
//2020-07-12T23:47:59.154+09:00[Asia/Tokyo]
ZonedDateTime dateAndTimeInTokyo = ZonedDateTime.of(now,ZoneId.of("Asia/Tokyo"));
相关标签: java基础