How to subtract X days from a date using Java calendar?

后端 未结 10 1251
無奈伤痛
無奈伤痛 2020-11-22 15:40

Anyone know a simple way using Java calendar to subtract X days from a date?

I have not been able to find any function which allows me to directly subtract X days fr

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 15:59

    It can be done easily by the following

    Calendar calendar = Calendar.getInstance();
            // from current time
            long curTimeInMills = new Date().getTime();
            long timeInMills = curTimeInMills - 5 * (24*60*60*1000);    // `enter code here`subtract like 5 days
            calendar.setTimeInMillis(timeInMills);
            System.out.println(calendar.getTime());
    
            // from specific time like (08 05 2015)
            calendar.set(Calendar.DAY_OF_MONTH, 8);
            calendar.set(Calendar.MONTH, (5-1));
            calendar.set(Calendar.YEAR, 2015);
            timeInMills = calendar.getTimeInMillis() - 5 * (24*60*60*1000);
            calendar.setTimeInMillis(timeInMills);
            System.out.println(calendar.getTime());
    

提交回复
热议问题