2

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?

1
  • Here is the 'official' tutorial focused on 1.8. Commented Jan 3, 2014 at 3:07

5 Answers 5

10
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) 
Sign up to request clarification or add additional context in comments.

12 Comments

@Alex the above allows for more customisable situations. Plus, it explains the logic for calculating time which is useful to anyone.
@Alex Say he wants to then do it in some other language without the same libraries. How does he do it without knowing the logic behind it? Ask again based on that language? I agree, code should be to the point - but there is a time and place for that.
This approach is error-prone (and you showed it). Try printing dateAgo and you will be surprised with result. It is better to use build in methods to avoid surprises like integer overflow.
The problem with is approach is it to easy to trip over irregularities in date/time. Not every day is is exactly 24 hours long and leap years, century and millennium boundaries all add it additional considerations...
Dont use 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.
|
8

Most of Date is actually deprecated, it has been superseded by Calendar:

Calendar.getInstance().add(Calendar.WEEK_OF_YEAR, -12); 

Comments

6

Use LocalDate.minusWeeks of JDK 1.8,

 LocalDate first=LocalDate.now(); LocalDate second=first.minusWeeks(12); 

1 Comment

because everyone runs Java 8.
3

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 

Comments

2
DateUtils.addWeeks(new Date(), -12); 

More about DateUtils.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.