JDK1.8的日期时间工具类

操作日期类LocalDate

太方便了,提供了非常多的方法,比之前的DateFormat好用多了,直接上代码

//给定日期

LocalDate date=LocalDate.of(2018,12,2);
System.out.println(date);
System.out.println(date.getYear());//取年份
System.out.println(date.getMonthValue());//取月份
System.out.println(date.getDayOfMonth());//取日期
System.out.println(date.getDayOfWeek().getValue());//取星期
//格式化日期
String dateValue=date.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
System.out.println(dateValue);
//判断润年
System.out.println(date.isLeapYear());
//根据日期字符串构造
LocalDate date1=LocalDate.parse("2020-08-02");
System.out.println(date1);
LocalDate date2= LocalDate.now();
//取本月第1天
System.out.println(date2.with(TemporalAdjusters.firstDayOfMonth()));
//取本月最后1天
System.out.println(date2.with(TemporalAdjusters.lastDayOfMonth()));
//取本月指定天数
System.out.println(date2.withDayOfMonth(10));
//取下n天
System.out.println(date2.plusDays(365));
//取给定时间月份的第一个周一
System.out.println(LocalDate.parse("2020-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)));

操作时间类LocalTime

LocalTime time=LocalTime.now();//取当前时间,默认带毫秒
time=LocalTime.now().withNano(0);//去除毫秒
time=LocalTime.now().plusHours(2);//2小时后的时间
time=LocalTime.now().plusMinutes(30);//30分钟后的时间
System.out.println(time);

操作日期时间类 LocalDateTime

与上面差不多,只是可以带日期和时间,不再赘述

Duration类用来获取两个LocalTime或LocalDateTime相差的时间

LocalTime time1 = LocalTime.now();
LocalTime time2 = LocalTime.now().plusHours(2).plusMinutes(30);
Duration duration = Duration.between(time1, time2);
System.out.println(duration.getSeconds());

Period类用来获取两个LocalDate相差的日期

LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.now().plusDays(3);
Period period = Period.between(date1, date2);
System.out.println(period.getDays());

获取指定时区的时间

ZonedDateTime time=ZonedDateTime.now();
System.out.println(time);
ZoneId zone = ZoneId.of("Europe/Paris");//美丽的巴黎
//获取指定的时区时间
ZonedDateTime paris = ZonedDateTime.now(zone);
System.out.println(paris);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值