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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章