0

I am using <sx:datetimepicker name="date1" label="From" displayFormat="yyyy-MM-dd"/> for picking the date. How ever I have to compare the picked date with date in mySQl table. The problem here is, the date in mySQl table is like 2014-09-29 20:36:25 and the format of piked date from struts2 tag is like Wed Dec 31 00:00:00 IST 2014. I am unable to compare both. Can any one tell me how to compare both? Or if I can change the format of picked time in java, how to do that?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Aadya
  • 75
  • 10
  • you can use SimpleDateFormat class in java to change the format – Ye Win Dec 23 '14 at 09:50
  • Dates don't have a format, only the strings you create to represent a date. – Peter Lawrey Dec 23 '14 at 09:50
  • A date [is just a single point in time](http://stackoverflow.com/a/27145350/1654265). It's up to you to format it properly, but since you are not doing String comparison, just obtain a Date from the page, a Date from the database and compare the dates, not their representation. – Andrea Ligios Dec 23 '14 at 09:51
  • I want to compare dates like this `select * from users where dateOfRegistration>=(pickedDate);` – Aadya Dec 23 '14 at 09:54
  • `select * from users where dateOfRegistration>= :pickedDate`. Then add the `pickedDate` parameter, using your date parsed with a SimpleDateFormat (or automatically by the framework). You should also avoid using the old – Andrea Ligios Dec 23 '14 at 10:07
  • possible duplicate of [Java & SQL comparing dates](http://stackoverflow.com/questions/14757836/java-sql-comparing-dates) – Basil Bourque Dec 25 '14 at 09:38

1 Answers1

0

You need to parse both Date to some same format so that you can compare that ..

see below code that can help you

public class Test {

public static void main(String[] args) {
    SimpleDateFormat sdfForSturtsDate = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
    SimpleDateFormat sdfForMySqlDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    String DateFromSturts = "Wed Dec 31 00:00:00 IST 2014";
    String DateFromMysql = "2014-09-29 20:36:25";
    java.util.Date dateFromsturts= new java.util.Date();
    java.util.Date dateFromMySql= new java.util.Date();
    try {
        dateFromsturts = sdfForSturtsDate.parse(DateFromSturts);
        dateFromMySql = sdfForMySqlDate.parse(DateFromMysql);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // now you can compare dateFromsturts and dateFromMySql
}

}

Keval
  • 1,857
  • 16
  • 26
  • "Wed Dec 31 00:00:00 IST 2014". this is the value of date object, it is not string. I am not able to cast date to string. – Aadya Dec 23 '14 at 14:49