this is my first time asking, I couldn't find explanation in all internet, so here you go: I'm writing a simple function to calculate the date that was x days ago, so I wrote this code that was working very ok, until today, the calculated past date was 1 year in the future, but not for all the values, only 11 days ago, the rest was ok. If you execute this code today you'll have this output: you can execute it here
difference:-11
2015-12-28
difference:-12
2014-12-27
As you can see, I though it was an issue parsing from Calendar to Date, also I've check that in Calendar the values were totally ok, but the moment I transfer to Date it doesn't work, I tried to do this cast manually but the functions are deprecated.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(getDate(-11, "YYYY-MM-dd"));
System.out.println(getDate(-12, "YYYY-MM-dd"));
}
public static String getDate(int offset, String SimpleFormat) {
DateFormat dateFormat = new SimpleDateFormat(SimpleFormat);
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, offset);
Date todate1 = cal.getTime();
long diff = todate1.getTime()-(new Date()).getTime();
System.out.println("difference:"+diff/ (24 * 60 * 60 * 1000));
String fromdate = dateFormat.format(todate1);
return fromdate;
}
}
Later I found a nice library called Joda-Time very nice and fast, so I changed the code to work with it, but surprise the same issue.
DateFormat dateFormat = new SimpleDateFormat(SimpleFormat);
DateTime today = new DateTime();
String fromdate = dateFormat.format(today.plus(Period.days(offset)).toDate());
So far I've also check that adding 350 days or so, into this 11 days period it gives a wrong date too. I know I can use Joda-time formatter, but still I can't find exactly what's the problem, any help would be nice :)
(for the ones who ever had this issue):
DateTimeFormatter fmt = DateTimeFormat.forPattern(SimpleFormat);
The problem isn't with the Date or DateTime, but rather with the formatter.
YYYY
means the ISO Week Year. However, the ISO Week year for the last partial week of the year is the next year.
yyyy
means the calendar year, which is what you really wanted.