Java8新特性之日期处理

日期处理

在Java8之前,操作日期的话不是很方便,有些地方需要自己编程实现。在Java8中的java.time包下新增很多关于日期处理的类,通过这些类可以使开发者更便捷的操作日期,这些类都是final修饰的,并且是线程安全的。

LocalDate类

LocalDate类只能操作日期相关的数据,不包含时间

//LocalDate 类
		//LocalDate类只能操作和日期相关的数据不包含时间
		
		LocalDate date1 = LocalDate.now();
		System.out.println(date1); //2019-03-11

		int year = date1.getYear();
		int month = date1.getMonthValue();
		int day = date1.getDayOfMonth();
		
		
		//格式化日期
		String s1 = date1.format(DateTimeFormatter.ofPattern("YYYY年MM月DD日"));
		System.out.println(s1);
		
		
		//判断闰年
		boolean leap = date1.isLeapYear();
		
		//获取该月份有 几天
		int len = date1.lengthOfMonth();
		System.out.println(len);
		

LocalTime类

LocalTime类只能操作时间相关的数据,不包含日期

LocalTime time1 = LocalTime.now().withNano(0);
		System.out.println(time1);
		
		//设置时间
		LocalTime time2 = LocalTime.of(6, 30, 20);
		System.out.println(time2);
		
		
		LocalTime time3 = LocalTime.parse("18:20:20");
		System.out.println(time3);

LocalDateTime类

LocalDateTime类可以处理日期和时间的数据

//LocalDateTime类
		LocalDateTime time = LocalDateTime.now();
		System.out.println("当前的时间为:"+time);

Duration和Period

Duration类用来 获取 两个 LocalTime相差的时间
Period类用来获取两个LocalDate相差的日期

//计算两个LocalTime相差的时间
		LocalTime time7 = LocalTime.of(7, 20);
		LocalTime time8 = LocalTime.of(7, 30);
		Duration duration = Duration.between(time7, time8);
		System.out.println("二者相差的时间秒数为:"+duration.getSeconds());
//计算祖国从建国道现在 过了多少年多少月多少日
		//建国日期
		LocalDate begin = LocalDate.of(1949, 10, 1);
		//今天日期
		LocalDate end = LocalDate.now();
		System.out.println("祖国已经成立");
		System.out.println(Period.between(begin, end).getYears()+"年");
		System.out.println(Period.between(begin, end).getMonths()+"月");
		System.out.println(Period.between(begin, end).getDays()+"日");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值