JAVA对时间进行加减年月日时分秒操作

两个时间进行年月日时分秒操作

    public static void testDate(Date timeOneForDate,Date timeTowForDate) throws ParseException {
        //定义时间操作类
        Calendar cal=Calendar.getInstance();
        SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("HH:mm:ss");
        String date = dateFormat1.format(timeOneForDate);
        String timeOne = dateFormat2.format(timeOneForDate);
        String timeTow = dateFormat2.format(timeTowForDate);
        //分割日期
        String[] dateOne = date.split("-");
        int yearOne = Integer.parseInt(dateOne[0]);
        int monthOne = Integer.parseInt(dateOne[1]);
        int dayOne = Integer.parseInt(dateOne[2]);
        //分割时间
        String[] splitOne = timeOne.split(":");
        int hhOne = Integer.parseInt(splitOne[0]);
        int mmOne = Integer.parseInt(splitOne[1]);
        int ssOne = Integer.parseInt(splitOne[2]);
        //写入年月日时分秒
        cal.set(Calendar.YEAR,yearOne);//年
        cal.set(Calendar.MONTH,(monthOne - 1));//月
        cal.set(Calendar.DAY_OF_MONTH,dayOne);//日
        cal.set(Calendar.HOUR_OF_DAY, hhOne);//时
        cal.set(Calendar.MINUTE, mmOne);//分
        cal.set(Calendar.SECOND, ssOne);//秒
        System.out.println("未进行计算的时间:\t"+dateFormat3.format(cal.getTime()));
        //分割时间
        String[] splitTow = timeTow.split(":");
        int hhTow = Integer.parseInt(splitTow[0]);
        int mmTow = Integer.parseInt(splitTow[1]);
        int ssTow = Integer.parseInt(splitTow[2]);
        //这里进行操作
        cal.add(Calendar.DAY_OF_MONTH,0);//操作天
        cal.add(Calendar.HOUR_OF_DAY, (hhTow * 1));//操作时-->Calendar.HOUR_OF_DAY为24小时制
        cal.add(Calendar.MINUTE, (mmTow * -1));//操作分
        cal.add(Calendar.SECOND, (ssTow * -1));//操作秒
        System.out.println("已进行计算的时间:\t"+dateFormat3.format(cal.getTime()));
    }

简单调用

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date timeOneForDate = dateFormat1.parse("2020-12-31 20:00:00");
        Date timeTowForDate = dateFormat1.parse("2020-10-10 10:30:30");
        testDate(timeOneForDate,timeTowForDate);
    }

得到结果

未进行计算的时间:	2020-12-31 20:00:00
已进行计算的时间:	2021-01-01 05:29:30
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值