How to subtract X days from a date using Java calendar?
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 from a date in Java. Can someone point me to the right direction?
Asked by: Grace284 | Posted: 23-01-2022
Answer 1
Taken from the docs here:
Answered by: Anna544 | Posted: 24-02-2022Adds 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).
Answer 2
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.
Answer 3
Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.
FYI in Joda Time you could do
DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);
Answered by: Wilson143 | Posted: 24-02-2022
Answer 4
tl;dr
LocalDate.now().minusDays( 10 )
Better to specify time zone.
LocalDate.now( ZoneId.of( "America/Montreal" ) ).minusDays( 10 )
Details
The old date-time classes bundled with early versions of Java, such as java.util.Date
/.Calendar
, have proven to be troublesome, confusing, and flawed. Avoid them.
java.time
Java 8 and later supplants those old classes with the new java.time framework. See Tutorial. Defined by JSR 310, inspired by Joda-Time, and extended by theThreeTen-Extra project. The ThreeTen-Backport project back-ports the classes to Java 6 & 7; the ThreeTenABP project to Android.
The Question is vague, not clear if it asks for a date-only or a date-time.
LocalDate
For a date-only, without time-of-day, use the LocalDate
class. Note that a time zone in crucial in determining a date such as "today".
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
LocalDate tenDaysAgo = today.minusDays( 10 );
ZonedDateTime
If you meant a date-time, then use the Instant
class to get a moment on the timeline in UTC. From there, adjust to a time zone to get a ZonedDateTime
object.
Instant now = Instant.now(); // UTC.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
ZonedDateTime tenDaysAgo = zdt.minusDays( 10 );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Answer 5
int x = -1;
Calendar cal = ...;
cal.add(Calendar.DATE, x);
See java.util.Calendar#add(int,int)
Answer 6
Instead of writing my own addDays
as suggested by Eli, I would prefer to use DateUtils
from Apache. It is handy especially when you have to use it multiple places in your project.
The API says:
addDays(Date date, int amount)
Adds a number of days to a date returning a new object.
Note that it returns a new Date
object and does not make changes to the previous one itself.
Answer 7
I faced the same challenge where I needed to go back by 1 day (should be able to roll back by one even if previous day falls into previous year or months).
I did following, basically subtracted by 24 hours for 1 day. someDateInGregorianCalendar.add(Calendar.HOUR, -24);
Alternatively, I could also do
GregorianCalendar cal = new GregorianCalendar();
cal.set(Calendar.YEAR, 2021);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DATE, 1);
System.out.println("Original: " + cal.getTime());
cal.add(Calendar.DATE, -1);
System.out.println("After adding DATE: " + cal.getTime());
OUTPUT:
Original: Fri Jan 01 15:08:33 CET 2021
After adding DATE: Thu Dec 31 15:08:33 CET 2020
Answered by: Dainton913 | Posted: 24-02-2022
Answer 8
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());
Answered by: David432 | Posted: 24-02-2022
Answer 9
I believe a clean and nice way to perform subtraction or addition of any time unit (months, days, hours, minutes, seconds, ...) can be achieved using the java.time.Instant class.
Example for subtracting 5 days from the current time and getting the result as Date:
new Date(Instant.now().minus(5, ChronoUnit.DAYS).toEpochMilli());
Another example for subtracting 1 hour and adding 15 minutes:
Date.from(Instant.now().minus(Duration.ofHours(1)).plus(Duration.ofMinutes(15)));
If you need more accuracy, Instance measures up to nanoseconds. Methods manipulating nanosecond part:
minusNano()
plusNano()
getNano()
Also, keep in mind, that Date is not as accurate as Instant. My advice is to stay within the Instant class, when possible.
Answered by: Miranda556 | Posted: 24-02-2022Answer 10
Someone recommended Joda Time so - I have been using this CalendarDate class http://calendardate.sourceforge.net
It's a somewhat competing project to Joda Time, but much more basic at only 2 classes. It's very handy and worked great for what I needed since I didn't want to use a package bigger than my project. Unlike the Java counterparts, its smallest unit is the day so it is really a date (not having it down to milliseconds or something). Once you create the date, all you do to subtract is something like myDay.addDays(-5) to go back 5 days. You can use it to find the day of the week and things like that. Another example:
CalendarDate someDay = new CalendarDate(2011, 10, 27);
CalendarDate someLaterDay = today.addDays(77);
And:
//print 4 previous days of the week and today
String dayLabel = "";
CalendarDate today = new CalendarDate(TimeZone.getDefault());
CalendarDateFormat cdf = new CalendarDateFormat("EEE");//day of the week like "Mon"
CalendarDate currDay = today.addDays(-4);
while(!currDay.isAfter(today)) {
dayLabel = cdf.format(currDay);
if (currDay.equals(today))
dayLabel = "Today";//print "Today" instead of the weekday name
System.out.println(dayLabel);
currDay = currDay.addDays(1);//go to next day
}
Answered by: Adelaide935 | Posted: 24-02-2022
Answer 11
Eli Courtwright second solution is wrong, it should be:
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -days);
date.setTime(c.getTime().getTime());
Answered by: Rafael913 | Posted: 24-02-2022
Similar questions
subtract hours as string in Calendar Instance in java
I have the hours format in string as 24hours format..."YYYYmmddHHmmss"(year,month,date,hours,mins,seconds)
suppose if i pass the hours as 2hours means,it should subtract 2 hours from the currentDateTime like "20110217182000";...("20110217182000" - 2hours)
what is the problem na,
the current hours is like as "201102*17000000*",after subtracting this hour as should come with yesterday date...like the answer "201102*...
java - How to subtract hours from a calendar instance
Based on my understanding of the roll() method, I expected the below code to subtract 140 hours from the current time. But it seems to be subtracting 20 hours. Is this not the proper way to do this?
Calendar rightNow = Calendar.getInstance();
rightNow.roll(Calendar.HOUR, -140);
java - How do you subtract different units of time using Calendar
This question already has answers here:
java - Subtract days from Current Date using Calendar Object
I am trying to subtract days from the current date using the java.util.Calendar object. My problem here is the days to subtract can be positive or negative. My code is as follows
public class Test {
public static void main(String[] args) {
int pastValidationDays=2;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, - pastValidationDays);
}
}
Android Java : How to subtract two times?
I use some kind of stopwatch in my project and I have
start time ex: 18:40:10 h
stop time ex: 19:05:15 h
I need a result from those two values like final time = stop - start
I found some examples but they all are very confusing .
Is there any simple solution ?
Java: Subtract '0' from char to get an int... why does this work?
This works fine:
int foo = bar.charAt(1) - '0';
Yet this doesn't - because bar.charAt(x) returns a char:
int foo = bar.charAt(1);
It seems that subtracting '0' from the char is casting it to an integer.
Why, or how, does subtracting the string '0' (or is it a char?) convert another char in to an integer?
subtract hours as string in Calendar Instance in java
I have the hours format in string as 24hours format..."YYYYmmddHHmmss"(year,month,date,hours,mins,seconds)
suppose if i pass the hours as 2hours means,it should subtract 2 hours from the currentDateTime like "20110217182000";...("20110217182000" - 2hours)
what is the problem na,
the current hours is like as "201102*17000000*",after subtracting this hour as should come with yesterday date...like the answer "201102*...
Java subtract two ints, result should be a minimum of zero
I want to subtract one integer from another, and the result should floor at 0. So 2 minus 4 should equal 0. I could just do
int result = x - y;
if (result < 0) result = 0;
But is there a more elegant way?
java - How to subtract 45 days from from the current sysdate
This question already has answers here:
Sum and subtract chars in Java and always get result within the ASCII range
I have created two functions that sum and subtract the numeric values of two chars and return the char of the result in PHP. It's something like this:
function sumchars($c1, $c2) {
return chr(ord($c1) + ord($c2));
}
function subchars($c1, $c2) {
return chr(ord($c1) - ord($c2));
}
Well, I also created these two function in Java and they are supposed to work as the PHP ones.
java - Add and Subtract buttons on a JSP page aren't working
I am writing a simple web app that performs calculations. I have 2 buttons, for adding and subtracting, but they aren't working. I tried to use a switch statement and an if statement, but neither are working. Could you please assist me to understand the problem.
Here is my code...
<%
String name = (String) session.getAttribute("name");
if (name==null) {
name = reques...
java - Add or Subtract
basically what im trying to do is have a number of stock (lets say its, 100) and an inventory list displaying the stock sold or added . how do i code it to say if it is a minus number , on the inventory list, (e.g -55) to take it away or if it is a positive number (i.e 45 to add it on instead of taking it away) ??
Cheers
How to subtract n days from current date in java?
This question already has answers here:
Find a pair of string at integer and subtract, java
I have a string which contains a value:
12345 5
54321 4
98765 10
The first value is a number, the second value is a count. The string value is obtained by this code:
for(ClusterListBean bean : clusterList) {
line += bean.getMSISDN()+"\t"+bean.getRewardCount()+"\n";
}
Now I am reading a file which has same contents but different ...
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)