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