wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes how to convert a string to date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to convert a string to date" Watch "how to convert a string to date" New topic

how to convert a string to date

Srinivasa Maddi
Ranch Hand

Joined: Apr 18, 2007
Posts: 60

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.

Rajkamal Pillai
Ranch Hand

Joined: Mar 02, 2005
Posts: 443


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.

Srinivasa Maddi
Ranch Hand

Joined: Apr 18, 2007
Posts: 60
Hi Raj,

I tried the following code..

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

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

Joined: Oct 27, 2005
Posts: 19653

The month should be in uppercase: dd-MM-yyyy. mm in lowercase means minutes, so it is taking your current month each time.

How To Ask Questions How To Answer Questions
I agree. Here's the link: http://aspose.com/file-tools
subject: how to convert a string to date
Similar Threads
How to get all request stored in databse between two date
Compare two custom date input fields each having 3 inputText fields using validator
Converting String to util.Date and then sql.Date
ResultSet rs = prestatement.executeQuery()
Converting string to util.date & then sql.date to query a table