This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes How to get Yesterday's date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to get Yesterday Watch "How to get Yesterday New topic
Author

How to get Yesterday's date

smitha rai
Greenhorn

Joined: Jun 29, 2001
Posts: 18
How do I get a yesteday's date in java.sq.Date format? Appreciate if someone would provide me a sample code.

Tnx

Smitha
Scott Selikoff
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3700
    
    5

Use Calendar.newInstance() to get the current date then decrement it by 1 DAY using the Calendar API.


My Blog: Down Home Country Coding with Scott Selikoff
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

smitha rai
Greenhorn

Joined: Jun 29, 2001
Posts: 18
Thanks TONS
Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
Another way could be:



In one line!

And I think millis in a day is already defined somewhere in the standard api (or in apache commons.)


ASCII silly question, Get a silly ANSI.
Don Morgan
Ranch Hand

Joined: Jul 24, 2003
Posts: 84
Stuart, do you know if this would work properly in areas with Daylight Savings Time, where the number of hours in a day ends up being 23 hrs for one day in the spring and 25 hrs for one day in the fall?

You may also have problems if the system clock is changed (say, for example, to sync with some central time server). I always thought this was more of a theoretical problem than a practical problem, until I saw it cause issues on a real production system.

The joys of keeping time in a distributed system....I would probably stick with using the Calendar method, let the java library sort it out, and test to make sure they got it right.


Don Morgan, Founder
www.DeveloperAdvantage.com - FREE Audiobooks for Software Developers
Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
I see, I hadn;t thought of these complications. Thanks for pointing it out.
Don Morgan
Ranch Hand

Joined: Jul 24, 2003
Posts: 84
I wasn't 100% sure about the daylight savings time issue, so I tried it out. Yep, unless I made a mistake, it is a problem.

Here's the little test code (sorry about using the deprecated api...). I scroll through the dates, moving forward in 1000 second intervals (a bit over 16 minutes). "yesterday" would be incorrect for 1hr in the spring and 1hr in the fall.



Output:

Scott Selikoff
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3700
    
    5

It's good that you noticed the daylight savings time issues but I suggest not getting hung up on solving it. Rather, make sure the normal case is still fast. Keep in mind that this is a problem only 0.02% time, so it fixing it shouldn't slow down the remaining 99.98% of the cases.
[ January 06, 2006: Message edited by: Scott Selikoff ]
Don Morgan
Ranch Hand

Joined: Jul 24, 2003
Posts: 84
Without knowing the details of what the application is for, it is not possible to establish the winner in the performance vs correctness tradeoff (even vs cost of developer time solving it!).

I think though in most cases you would be correct.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Originally posted by Don Morgan:
Without knowing the details of what the application is for, it is not possible to establish the winner in the performance vs correctness tradeoff (even vs cost of developer time solving it!)
I think it is possible. If the code is going to be run rarely, then the performance aspects of doing some built-in Calendar logic over subtracting a magic number are going to be so small as to be negligible. So I would use the Calendar logic there. But if it is going to be run often enough to matter, then the number of times the "magic number" version is wrong will be noticeable twice a year (in some places). So I would use the Calendar logic there too.

Or to put it more bluntly, I would use correct logic in preference to faster but incorrect logic in almost all situations.
Scott Selikoff
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3700
    
    5

Originally posted by Paul Clapham:
Or to put it more bluntly, I would use correct logic in preference to faster but incorrect logic in almost all situations.

I think my original sentiment is that I sometimes see developers spending too much time on special cases that can rarely ever even happen. For example, if you spend 10 hours on the general solution, but 80 hours on a special case, you just have to think ahead and make sure the special case isn't a little too special, as in it almost never happens.

I'm all for correctness, but there is such a thing as going over board in special cases... with the one exception of concurrency issues. Its rare I see developers really considering concurrency issues when solving J2EE problems for things that only have 1-2 users in a test environment and thousands in a production environment.
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Originally posted by Paul Clapham:
I think it is possible. If the code is going to be run rarely, then the performance aspects of doing some built-in Calendar logic over subtracting a magic number are going to be so small as to be negligible. So I would use the Calendar logic there. But if it is going to be run often enough to matter, then the number of times the "magic number" version is wrong will be noticeable twice a year (in some places). So I would use the Calendar logic there too.

Or to put it more bluntly, I would use correct logic in preference to faster but incorrect logic in almost all situations.


Unless it's run very often and the error twice a year isn't important.
Susanta Chatterjee
Ranch Hand

Joined: Aug 12, 2002
Posts: 102
How about getting it from a database server. Like, if the database is Oracle, then get it from SYSDATE.

If there is no database, then of course this will not work. But if there is one, then that is the best way to do it.

- Susanta
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Frankly it seems rather premature to worry about speed at this point. Especially if that's used as justification for sacrificing correctness. There's no reason to think the performance is critical here, or that there's a bottleneck in this area. Aside from the issue of correctness, I'd want to think about readability and maintainability here before performance. And really, the code to do this correctly is fairly simple anyway:

Sure, it was easy to overlook the issue of daylight savings in this problem. It's quite understandable. But when professional programmers deal with dates & times, issues like daylight savings and leap years are exactly the sorts of things that we should try to anticipate. Especially where there's a standard library that can handle the situation for us.

It's unusal for me to speak well of the Calendar and GregorianCalendar classes - there are a number of ways in which they could have been - should have been - designed better. But that doesn't change the fact that this sort of problem is what they were designed to do. It's worthwhile to understand the capabilities of standard Java classes - especially anything in java.lang or java.util.
[ January 07, 2006: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Jack Punt
Greenhorn

Joined: Jun 13, 2009
Posts: 1
Excellent article, and cheers for the professional attitude to drive correctness over "premature optimization"

But I wonder how this function works to calculate getDateBefore(date) without reference to the 'date' parameter??
One might expect to see: cal.setTime(date) before cal.add(...)
Jason Irwin
Ranch Hand

Joined: Jun 09, 2009
Posts: 327
Allow me to stick my oar in with these two comments:
1) Whose time zone?
2) Whose Daylight Savings Time?

As you are dealing with a Date instance, 1) is probably moot. The trick is to know what date you are initially parsing and making sure that you have correctly interpreted it. if the Date instance is not constructed correctly, then you will never get the correct answer and adding "fudge factors" to try and cope with time zones after the fact is fraught with danger. My personal motto in dealing with dates is that any string date without a time zone is invalid, without exception. If you are always using Calendar.getInstance() (or similar) and not having to read a date from somewhere, then you don't have to worry about this.

2) can be a gotcha even if your code looks correct (usually affects client/server applications). Not all countries move to/from Daylight Savings at the same time, so you have to ensure that the value displayed to the user makes sense to them. One example could be a user in the UK using a server hosted in the USA, if the server (or client) cannot compensate for the differences in Daylight Savings Times the user could get values that are an hour out.

Is the odd hour out an issue? Depends on your circumstances. In most cases it's probably more annoying than anything. For audit systems and regulatory compliance then you could be in serious trouble.

I normally handle all this by ensuring dates are either passed around as proper Date/Calendar instances or fully formatted Strings to UTC following SI notation (ISO-8601). I have had to spend quite a lot of time over the past few years fixing a lot of code because people simply cannot tell the time! So, for my money, I'd use Paul's method as that 0.02% could end up biting you a few years down the line.

So, repeat after me, a string date without a time zone is invalid. Always.

J.


SCJP6
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

Please http://faq.javaranch.com/java/DontWakeTheZombies


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to get Yesterday's date
 
Similar Threads
How to get tomorrow's date?
How to get next date of a given date
date problem
dates in java
first date and last date of month