This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Get N-Days before today using Date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Get N-Days before today using Date" Watch "Get N-Days before today using Date" New topic
Author

Get N-Days before today using Date

Daesung Park
Ranch Hand

Joined: Mar 22, 2007
Posts: 68
Hi,

To get N-Days before today, I know Calendar.add() works fine.
But, I thought

will also work. So I wrote test code as below


But, it makes wrong results as below
1 days before: Sun Feb 01 15:31:20 KST 2009
2 days before: Sat Jan 31 15:31:20 KST 2009
3 days before: Fri Jan 30 15:31:20 KST 2009
4 days before: Thu Jan 29 15:31:20 KST 2009
5 days before: Wed Jan 28 15:31:20 KST 2009
6 days before: Tue Jan 27 15:31:20 KST 2009
7 days before: Mon Jan 26 15:31:20 KST 2009
8 days before: Sun Jan 25 15:31:20 KST 2009
9 days before: Sat Jan 24 15:31:20 KST 2009
10 days before: Fri Jan 23 15:31:20 KST 2009
11 days before: Thu Jan 22 15:31:20 KST 2009
12 days before: Wed Jan 21 15:31:20 KST 2009
13 days before: Tue Jan 20 15:31:20 KST 2009
14 days before: Mon Jan 19 15:31:20 KST 2009
15 days before: Sun Jan 18 15:31:20 KST 2009
16 days before: Sat Jan 17 15:31:20 KST 2009
17 days before: Fri Jan 16 15:31:20 KST 2009
18 days before: Thu Jan 15 15:31:20 KST 2009
19 days before: Wed Jan 14 15:31:20 KST 2009
20 days before: Tue Jan 13 15:31:20 KST 2009
21 days before: Mon Jan 12 15:31:20 KST 2009
22 days before: Sun Jan 11 15:31:20 KST 2009
23 days before: Sat Jan 10 15:31:20 KST 2009
24 days before: Fri Jan 09 15:31:20 KST 2009
25 days before: Fri Feb 27 08:34:08 KST 2009

Can you explain what the problem is?

Daesung Park

BLOG
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

What would happen if you declared N to be a long instead of an int, and try to figure out why the result would be different.


[My Blog]
All roads lead to JavaRanch
Daesung Park
Ranch Hand

Joined: Mar 22, 2007
Posts: 68
What a silly mistake! Thanks Christophe

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Daesung Park wrote:But, I thought

will also work.

It would, if it weren't for that pesky thing called daylight savings time. Although the date itself will still be correct if the code is not called between 11 PM and 1 AM, the time most definitely will not. And the date can also be incorrect if called between 11 PM and 1 AM. Calendar.add fixes these possible errors.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
GeeCON Prague 2014
 
subject: Get N-Days before today using Date