• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to convert a string to date

 
Srinivasa Maddi
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have a form containing two text fields (one for fromDate & other for toDate). I am capturing these two field values entered by the user. Now i want to compare these two date's(which are in string format) so that the fromDate should not be greater than toDate. I am unable to understand the Calendar technique which i assume to be applied here.

Regards,
Maddi
 
Rajkamal Pillai
Ranch Hand
Posts: 445
1
Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

You can create a java.text.SimpleDateFormat object passing the format of the date entered (Ex:- mm/dd/yyyy hh:mm:ss). Then call a parse function passing the value entered by the user. The parse() function returns a java.util.Date object which can then be used for comparison operations as necessary.

Cheers,
Raj.
 
Srinivasa Maddi
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Raj,

I tried the following code..

....
....
DateFormat df = new SimpleDateFormat ("dd-mm-yyyy");
Date d1 = null;
Date d2 = null;
try{
d1 = df.parse(fromDate);
d2 = df.parse(toDate);
}
catch(Exception e)
{
System.out.println("Exception while parsing date...");
e.printStackTrace();
}

...
...
if (d1.after(d2))
{
System.out.println("From date should not be greater than To date");
}
The above piece of code works fine but not consistently. For example the comparision fails if you try with the following values

fromDate = 12-10-2008
toDate = 13-11-2008

Kindly suggest a solution
 
Rob Spoor
Sheriff
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The month should be in uppercase: dd-MM-yyyy. mm in lowercase means minutes, so it is taking your current month each time.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic