aspose file tools*
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
Author

how to convert a string to date

Srinivasa Maddi
Ranch Hand

Joined: Apr 18, 2007
Posts: 60
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

Joined: Mar 02, 2005
Posts: 443
    
    1

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

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;
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

Joined: Oct 27, 2005
Posts: 19670
    
  18

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
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