• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to compare two different format date

 
Phoebe Song
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a assignment and it is urgent. I have two dates, one is String and the format is "mm/dd/yyyy", and other is Date, format is "mm-dd-yyyy". How can I change format from one to other so I can compare? Thanks in advance.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15354
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use the class java.text.SimpleDateFormat (look it up in the API documentation) to convert the strings with the dates to java.util.Date objects. Then you can use methods in class Date like equals(), before(), after() to compare the two dates.
 
Phoebe Song
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried that before, but always got a exception. Then I tried to use this code:

DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
Date parsedate = df.parse(csdate);
java.sql.Date csdate = new java.sql.Date(parsedate.getTime());

The only prolem is when I parse the csdate which is a String has the format mm/dd/yyyy, Semptember became January

I was thinking the other way around, how can I change sql date mm-dd-yyyy to String mm/dd/yyyy? Thanks.
[ September 27, 2007: Message edited by: Phoebe Song ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can rearrange strings with substrings and concatenation to put them both in yyyy/mm/dd format, and then they'll compare correctly.

But it would be a lot more educational to figure out the Date approach. Hang in there until you make this work just so you can say you know Date. See if upper case MM helps in your pattern. Lower case mm is minutes. Once you get parsing working, you can use one date format to parse and another to format back to string. Something along the lines ...

And just for grins, I have a string function based on REXX: translate(input,outtable,intable). For each character of the input, if that character is found in InTable, it is replaced with the corresponding character from OutTable. The conventional use is:

See what this alternative usage does:

And it was about 100x faster than the Date technique last time I checked.
 
Phoebe Song
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much Stan James!

When I change mm to MM it works!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic