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.
D Wynn
Ranch Hand
Joined: May 03, 2004
Posts: 38
posted
0
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.
I'm getting this output... B 8-18-2006 3:41 B 2006-08-19 00:00:00.0 Date Wed Jan 18 03:41:00 CST 2006 Date2 Sun Jan 08 00:00:00 CST 0019 Date3 Sun Jan 15 00:15:00 CST 2006
Originally posted by D Wynn: The the dates I'm trying to parse are Aug dates I'm confused as to why the parsed dates I get back are Jan. dates. I must be missing something
Please re-read Michael's (the previous) post -- basically, you are processing the month field as minutes. It is January, because that is the default value when it is not assigned.