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

后端 未结 10 1252
無奈伤痛
無奈伤痛 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条回答
  •  不要未来只要你来
    2020-11-22 15:51

    You could use the add method and pass it a negative number. However, you could also write a simpler method that doesn't use the Calendar class such as the following

    public static void addDays(Date d, int days)
    {
        d.setTime( d.getTime() + (long)days*1000*60*60*24 );
    }
    

    This gets the timestamp value of the date (milliseconds since the epoch) and adds the proper number of milliseconds. You could pass a negative integer for the days parameter to do subtraction. This would be simpler than the "proper" calendar solution:

    public static void addDays(Date d, int days)
    {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.add(Calendar.DATE, days);
        d.setTime( c.getTime().getTime() );
    }
    

    Note that both of these solutions change the Date object passed as a parameter rather than returning a completely new Date. Either function could be easily changed to do it the other way if desired.

提交回复
热议问题