Hi-- I have a question I want to compare dates in a javaservlet one date I'm getting off the a database and the other date I'm using the Gregorian Calendar to go back 48 hours to get the other date. Right now when I get the date off the database I save it in string array and the other I was saving as a string also (when I first wrote the pgm I didn't need to compare date within the pgm I just used to date for my sql now I need to compare the two dates in the pgm). What's the easiest way to now compare the dates...the date coming from the db is used a lot already in the pgm as a string. Is there a way for me to cast both dates to compare them or do I need to look at storing it another way of the db?
Perhaps I'm missing something here . . . could you just create a static method that takes two String objects, tries to convert them to dates, and returns the difference (in milliseconds, or whatever you want). That way you don't have to change the rest of your application, but you can do the comparison.
Again, I may be missing something. It seems that my answer is pretty simplistic, so perhaps there more to the problem than I'm reading in your post.
If I were you, when I got the dates from the database I would keep them as dates (i.e. java.util.Date or java.sql.Date or java.util.Calendar or something like that). You'll notice that those classes all have "before" and "after" methods which are specifically designed for comparing dates or timestamps.
When you convert a date to a string, you make it much harder to compare to other dates. (Unless you use the ISO format which looks like YYYY-MM-DD, but you didn't, did you?) So keep the dates as dates, and format them into strings when it comes time to display them to a person.
Joined: May 03, 2004
I really don't want to touch my other code with it being so late in the game. So you're saying what I could do is convert the date strings first and then compare them or just compare the date stings without converting them? How can I do this?
No, don't compare dates stored as strings. That will cause more problems than it solves.
Paul's response is the best solution. Get the date from the database as a Date.
The next best solution is to convert the date string back to a Date object and compare Date objects. You can convert a date stored in a String to a Date by using the SimpleDateFormat class.
Joined: May 03, 2004
Question when I try and parse a string I get the wrong date what is going on..here is the code... SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy hh:mm"); java.util.Date date = null; java.util.Date date2 = null; java.util.Date date3 = null;