Java时间的加减处理

1 直接加减

采用的是Date类型的数据和Long类型的数据之间的转换

  1. Date转换为Long
long time = date.getTime();
  1. Long转换为Date
Date date2 = new Date(newTime);
//      把Date类型的日期转换为Long类型的数字,然后也可以进行上述的时间的加减操作
//        一天 = 24 * 60 * 60 * 1000 =86400000L
//        下面演示当前时间加30天

        Date date1 = new Date();
        long time = date.getTime();
        long newTime = time + 30 * 86400000L;
        Date date2 = new Date(newTime);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(date2);

2 采用GregorianCalendar转换

重点是GregorianCalendar 和Date之间的转换

  1. Date转换为GregorianCalendar
calendar.setTime(date);
  1. GregorianCalendar转换为Date
Date newDate = calendar.getTime();
//      日历类用于对Date类型的数据的 年、月、日、时、分、秒进行加减等运算处理
        Date date = new Date();
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(date);

//       此处为在当前日期上减去30年
        calendar.set(Calendar.YEAR, -30);
//        此处为在当前日期上增加30天
        calendar.set(Calendar.DATE, 30);

//        把日期转换为Date类型
        Date newDate = calendar.getTime();
//      设置日期的生成格式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//      转换后的日期是一个字符串类型不再是Date类型了
        String transFormDate = formatter.format(newDate);
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值