JDK1.8更便捷获取时间的方法:LocalDateTime、LocalDate、LocalTime、Period以及跟Date类型的转换

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;

public class test {

	public static void main(String[] args) {
		
		LocalDateTime now = LocalDateTime.now();
		System.out.println("当前时间 : " +  now); //注意: 这个会打印 年月日时分秒毫秒
	    System.out.println("5分钟后的时间 : " +  now.plusMinutes(5));
	    System.out.println("2小时后的时间 : " +  now.plusHours(2));
	    System.out.println("1星期后的时间 : " +  now.plusWeeks(1));
	    System.out.println("1个月后的时间 : " +  now.plusMonths(1));
	    System.out.println("1年后的时间 : " +  now.plusYears(1));
	    System.out.println("1年前的时间 : " +  now.plusYears(-1));//plusXXX方法是加
        System.out.println("1年前的时间 : " +  now.minusYears(1));// minusXXX方法是减
        System.out.println("修改后的时间 : " + now.withYear(2088));// 直接修改使用withXXX
        System.out.println("当天最大时间 : " + now.with(LocalTime.MAX));
        System.out.println("当天最小时间 : " + now.with(LocalTime.MIN));

        //原来获取某个时间之前的时间的方法
		Double tempTime = 1.5 * 3600 * 1000; //1.5H
        long time = new Date().getTime() - tempTime .longValue();
        System.out.println("1.5个小时前的时间 :" + new Date(time));
		Double tempTime1 = 1.5 * 24 * 3600 * 1000;//1.5天
		long time1 = new Date().getTime() - tempTime1.longValue();
        System.out.println("1.5天前的时间 :" + new Date(time1));

	    
	    LocalDate date = LocalDate.now();
        //注意: 这个只会打印 年月日
	    System.out.println("1天后的日期 : " +  date.plusDays(1)); 
	    
	    LocalTime time = LocalTime.now();
        //注意: 这个只会打印 时分秒毫秒
	    System.out.println("1小时后的时间 : " +  time.plusHours(1)); 
        
        //查看相差天数
        long days = Duration.between(LocalDateTime.now(), LocalDateTime.now().plusDays(1)).toDays();

        //创建一个1年,2个月,3天的间隔
	    Period period2 = Period.of(1, 2, 3);
        // 打印日期为date之后1年零2个月后3天的日期
	    System.out.println(date.plus(period2)); 
        
        //创建一个年月日时分秒的时间,传值年,月,日,时,分,秒,也可以传其他值可以自己尝试
        LocalDateTime tempDate = LocalDateTime.of(2022,2,2,12,15,01);
	    

        //转换成Date类型--mybatis早期版本不支持JDK1.8的LocalDate 、LocalDateTime 、LocalTime 类,直接使用mybatis保存到数据库会报错
		ZoneId zoneId = ZoneId.systemDefault();
		ZonedDateTime zonedDateTime = now.atZone(zoneId);
		Instant instant = zonedDateTime.toInstant();
		Date d = Date.from(instant);
        
        //Date转换成LocalDateTime 
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);


	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往事不堪回首..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值