How to Subtract X Days from a Date Using Java Calendar

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

Taken from the docs here:

Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:

Calendar calendar = Calendar.getInstance(); // this would default to now
calendar.add(Calendar.DAY_OF_MONTH, -5).

How to subtract X day from a Date object in Java?

Java 8 and later

With Java 8's date time API change, Use LocalDate

LocalDate date = LocalDate.now().minusDays(300);

Similarly you can have

LocalDate date = someLocalDateInstance.minusDays(300);

Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Java 7 and earlier

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

How to subtract X days from a given string field storing Date in java?

Date is being phased out, there are new classes you could use if you are OK with that (ie it is not compulsory to use Date). For example:

        String extractDate = "2020-11-13";
LocalDate date = LocalDate.parse(extractDate);
LocalDate newDate = date.minusDays(30);
System.out.println(newDate);

Unable subtract days from date in java

Use java.util.Calendar.
Something like that:

Calendar c = new Calendar()
c.setTime(currentDate);
c.add(Calendar.DAY_OF_MONTH, noOfDays)
compareDate = c.getTime()

How to subtract n days from current date in java?

You don't have to use Calendar. You can just play with timestamps :

Date d = initDate();//intialize your date to any date 
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 l ); //Subtract n days

UPDATE
DO NOT FORGET TO ADD "l" for long by the end of 1000.

Please consider the below WARNING:

Adding 1000*60*60*24 milliseconds to a java date will once in a great while add zero days or two days to the original date in the circumstances of leap seconds, daylight savings time and the like. If you need to be 100% certain only one day is added, this solution is not the one to use.

How to subtract 30 days from current date

Use below code

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
c.setTime(sdf.parse(date));
c.add(Calendar.DATE, -30);
Date newDate = c.getTime();


Related Topics



Leave a reply



Submit