Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Date in java

 
vidhya subramaniam
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can I get yesterday's date in java.
if i use
Date d = new Date() ---- its going to give me today's date.
I want to look into my program only for records from yesterday after 2 pm. how can i do that
thanks,
vidhya
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should use the GregorianCalendar class instead of the Date class. GregorianCalendar has a method named roll() which lets you easily change the date by any increment. You can also set the time to exactly 2:00 p.m. or whatever you wish.
HTH
Layne
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ack! You don't want to use roll() here - if the date is Jan 1, 2003 and you do
calendar.roll(Calendar.DATE, -1);
you will get Jan 31. Instead use add():
calendar.add(Calendar.DATE, -1);
This will get you to Dec 31, 2002 as expected.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to the API, GregorianCalendar doesn't have the same issues as its base class, Calendar. I just skimmed through it, though, so I may have misunderstood.
Layne
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure which part of the API you mean, but I think you misunderstood. Look carefully at the API for the roll(int, int) method, and compare it to the add(int, int) method.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the correction. I guess I should be more specific. I read the following in the documentation for Calendar.roll(), but I didn't go to the GregorianCalendar API to see if it had any caveats documented there.
Time Field Rolling function. Add to field a signed amount without changing larger fields. A negative roll amount means to roll down. [NOTE: This default implementation on Calendar just repeatedly calls the version of roll() that takes a boolean and rolls by one unit. This may not always do the right thing. For example, if the DAY_OF_MONTH field is 31, rolling through February will leave it set to 28. The GregorianCalendar version of this function takes care of this problem. Other subclasses should also provide overrides of this function that do the right thing.

Mostly, it just looked like it might work, so I was trying to point the original poster in the direction that would (hopefully) answer his question. I should put disclaimers on such advice in the future.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic