Posts Tagged ‘basic rules’
Dangerous Date manipulation
public static String getIncrementedDate(String someDate, int inc, String dateFormat) {
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
java.util.Date initDate = null;;
try {
initDate = formatter.parse(someDate);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
long Fech = initDate.getTime() + inc*24*60*60*1000;
Date incrementedDate = new Date(Fech);
return formatter.format(incrementedDate);
}
public static void main(String...strings ) throws Exception {
System.out.println(getIncrementedDate("20081026", 1, "yyyyMMdd"));
}
Maybe you are expecting “20081027″ output for this program? You’re wrong. This code produces “20081026″.
Changing the hour (from 3:00 AM to 2:00 AM) on 26th October involves a mathematical difference of 24 + 1 hours between 26th October and 27th October.
Don’t use java.util.Date to manipulate dates in Java. Use Calendar instead.