This caused a Y2K-style bug in my software if you can imagine. Strange thing is the off-by-one year calculation only occurs for two days in the year, which I'm less sure how to troubleshoot.
The output:
03-Jan-2013
02-Jan-2013
01-Jan-2013
31-Dec-2013 ** strange
30-Dec-2013 ** strange
29-Dec-2012
28-Dec-2012
27-Dec-2012
26-Dec-2012
25-Dec-2012
I am not sure which part of the Java date utilities could cause such an error.
The code (since the test is so small I included a complete working program):
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
public class DateT {
private static String getFormattedBackscanStartTime(int days) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-YYYY");
Calendar workingDate = Calendar.getInstance();
workingDate.add(Calendar.DATE, -1 * days);
String formattedStartTime = dateFormat.format(workingDate.getTime());
return formattedStartTime;
}
public static void main(String args[]) {
for(int i = 35; i < 45; i++) {
System.out.println(getFormattedBackscanStartTime(i));
}
}
}
For the sake of completeness, here’s the modern answer using
LocalDate
(as recommended by Basil Bourque in a comment).Running this today I got
A few things to note:
Locale.getDefault()
you are telling the reader that you have thought about locale and made a decision.LocalDate.now()
to tell the reader you’ve made a decision (for exampleZoneId.of("America/New_York")
for a specific time zone;ZoneId.systemDefault()
for the JVM’s current time zone setting).Calendar
class. This is typical for the newer classes.uuuu
for year.yyyy
(lowercase) works too, there will only be a difference for years before the common era (AKA BC).This is the problem:
YYYY
is the week-year, not the calendar year. You wantyyyy
instead.The last two days of calendar year 2012 were in the first week of week-year 2013. You should normally only use the week year in conjunction with the "week of year" specifier (
w
).I am assuming you are using
java 1.7
.The code snippet above will not work with
java 1.6
asSimpleDateFormat("dd-MMM-YYYY")
will raise anjava.lang.IllegalArgumentException
(YYYY is not available injava 1.6
)You need to use
yyyy
instead ofYYYY
.here
EDIT
Works great with
yyyy
:The problem lies in your date format string - year should be
yyyy
notYYYY
.If you print the value of
workingDate.getTime()
in each iteration of the loop, you'll see it has the expected values:Therefore the problem lies in the SimpleDateFormat usage.
You need to use lower case y for the year. Try this: