How to subtract X day from a Date object in Java?
To subtract a certain number of days from a Date
object in Java, you can use the Calendar
class. The Calendar
class allows you to manipulate the date and time values of a Date
object.
Here's an example of how you can subtract X days from a Date
object using the Calendar
class:
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// create a Calendar object and set it to the current date and time
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
// subtract 10 days from the calendar
calendar.add(Calendar.DAY_OF_MONTH, -10);
// get the modified Date object
Date date = calendar.getTime();
// print the date
System.out.println(date);
}
}
This code creates a new Calendar
object and sets it to the current date and time. It then subtracts 10 days from the calendar using the add
method and the Calendar.DAY_OF_MONTH
field. Finally, it gets the modified Date
object using the getTime
method and prints it to the console.
Note that the add
method allows you to add or subtract a certain number of days, months, years, etc. from the calendar. You can use the various fields of the Calendar
class (such as Calendar.DAY_OF_MONTH
, Calendar.MONTH
, Calendar.YEAR
, etc.) to specify the unit of time that you want to add or subtract.