I'm trying to subtract 5 days from a date which comes in as a string initially.
I have had a look at some of the other posts on this subject but the result i get from the code is always incorrect. The main problem is that the year value does not seem to change when the days are subtracted for example - 2012-01-01 subtract 5 days gives me 'Jan 27 2012'
using this code -
cal.add(Calendar.DATE, -5);
Please help.
Joda-Time
The Joda-Time 2.7 library makes this work much easier. Just call the
minusDays
method.If you want the beginning of the day, add a call to
withTimeAtStartOfDay
. This is unnecessary in your case, when parsing a date-only string with no time-of-day.If you want only date without time-of-day or time zone, use
LocalDate
instead of DateTime.If you need to convert to the old java.util.Date, call
toDate
on the DateTime.java.time
Java 8 has a new package, java.time. These new classes were inspired by Joda-Time but were re-architected. Both java.time and Joda-Time can solve this particular problem equally well.
Use:
EDIT: sorry.
DAY_OF_MONTH
is a synonym toDATE
. Instead of1
useCalendar.JANUARY
.This a segment of code that is working on my pc. first you have to get the calendar instance the perform your calculation.
This is the output that you will get:
Your implementation is correct and you are getting the correct value aslo.
Calendar
's Months started with0
so subtracting
5 days
from2012-01-01
will definitely returns youJan 27 2012
something is here also which will helps you Why is January month 0 in Java Calendar?Calendar.FEBRUARY is 1 and five days before 1 Feb 2012 was 27 Jab 2012.
Did you know that, in Java, month
1
is actually February?This might explain what you are seeing. If you want to instantiate 2012-01-01 instead, you should do:
Exactly the same thing happens when dealing with
Calendar
:Be sure to check the documentation for
Date(int, int, int)
andCalendar.set(int, int, int)
. Also, you could check the way you are parsing the string. If you useSimpleDateFormat.parse(...)
, things can be easier.Strange, isn't it? Go figure... Just as a fun fact, IntelliJ's documentation annotates this second parameter, month, with
@MagicConstant
, to remember the programmer that there's something very strange going on.