• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

how to convert a string to date

 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 479
1
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 22821
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
For my next feat, I will require a volunteer from the audience! Perhaps this tiny ad?
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic