I know I can get the current date using new Date(), but I want to get a past date (12 weeks back). For example: today is Jan 3rd 2014, a 12 weeks old date would be Oct 11 2013.
How to do that in java?
I know I can get the current date using new Date(), but I want to get a past date (12 weeks back). For example: today is Jan 3rd 2014, a 12 weeks old date would be Oct 11 2013.
How to do that in java?
Date date = new Date(); long timeAgo = 1000L * 60 * 60 * 24 * 7 * 12; Date dateAgo = new Date(date.getTime() - timeAgo); Should work just fine. Don't miss the L from the multiplication, otherwise you'll get overflow results. Good spot by Pshemo.
FYI, the timeAgo columns are as follows:
1000 is representative of a second (1000 milliseconds) 1000 * 60 is representative of a minute (60 seconds) 1000 * 60 * 60 is representative of an hour (60 minutes) 1000 * 60 * 60 * 24 is representative of a day (24 hours) 1000 * 60 * 60 * 24 * 7 is representative of a week (7 days) 1000 * 60 * 60 * 24 * 7 * 12 is representative of 12 weeks (12 weeks) dateAgo and you will be surprised with result. It is better to use build in methods to avoid surprises like integer overflow.l to specify long (it looks more like 1). Use L instead. Also try adding this suffix to your first operand 1000L to make result of first multiplying (and by that also others) long. It helps making sure that you will not overflow integer before you will multiply it with last operand 12L.Most of Date is actually deprecated, it has been superseded by Calendar:
Calendar.getInstance().add(Calendar.WEEK_OF_YEAR, -12); Use LocalDate.minusWeeks of JDK 1.8,
LocalDate first=LocalDate.now(); LocalDate second=first.minusWeeks(12); I am surprised no one mentioned Joda Time yet.
DateTime dt = new DateTime(); System.out.println(dt); System.out.println(dt.minusWeeks(12)); System.out.println(dt.minusWeeks(12).toDate());//if you prefer Date object Output:
2014-01-03T04:40:40.402+01:00 2013-10-11T04:40:40.402+02:00 Fri Oct 11 04:40:40 CEST 2013