| Author |
how can i get yesterdays date?
|
Robert Johnson
Ranch Hand
Joined: Feb 11, 2005
Posts: 32
|
|
java.util.Date todaysDate = new java.util.Date(); thats todays date but how wud i go about geting yesters date? is there any way i can say 'take one day off todaysDate' to get yesterdays date?
|
Whats in a name?
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26496
|
|
Robert, Yes! You need to use a calendar instead of a date at first: [edited to add -1 instead of 1] [ March 27, 2005: Message edited by: Jeanne Boyarsky ]
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
Robert Johnson
Ranch Hand
Joined: Feb 11, 2005
Posts: 32
|
|
Calendar cal = new GregorianCalendar(); // creates with today's date cal.add(1, Calendar.DATE); Date yesterday = cal.getTime();
sure u dont "add 1" ?? should that be a -1 ?? i just after found these on the web. I'll try the three. Thanks for replying. Calendar theDate = Calendar.getInstance(); // returns a new locale-specific calendar set to the current time. theDate.add(Calendar.DATE, -1); This converts todays date in milliseconds. Then subtracts the number of milliseconds in 24 hrs (24*60*60*1000) from it. Thenit makes a date object by using above calculated milliseconds into constructor. Date mydate=new Date(); long mymillidate=mydate.getTime(); mymillidate=mymillidate - 24*60*60*1000; Date previousdate= new Date(mymillidate);
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26496
|
|
Robert, Yes, it should be a -1. I edited my post. Thanks for pointing this out. I prefer using the calendar method than dealing with milliseconds. It makes the intent of what you are trying to do clearer.
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
The calendar also takes care of things like daylight savings for you. Otherwise you might go from 12 noon to 1 PM or 11 AM when you cross a transition. In general I despise the Calendar API as being unnecessarily convoluted and confusing. And so I avoid it whenever possible. But this problem is precisely the sort of task that GregorianCalendar is cut out for. [ March 27, 2005: Message edited by: Jim Yingst ]
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: how can i get yesterdays date?
|
|
|