javadate-parsingjava.util.date

Date convert in Java


I want to compare two dates, for that i convert the string to date format.But during the conversion the date format changed to "02/01/2013" and "03/01/2014".It makes error in my logic.any one please tell me to how to compare two days in my date format.

      String fdate="01/02/2012";
      String tdate="01/03/2013";
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
      Date frmdt=new Date(fdate);
      String s1 = sdf.format(frmdt);
      Date todt=new Date(tdate);
      String s2 = sdf.format(todt);
      Date frmdate = sdf.parse(s1);
      Date todate = sdf.parse(s2);
      if(frmdate.compareTo(todate)<=0){
          // process;      
      }

I expected s1 to be the same as fdate, 01/02/2012; but it is 02/01/2012. Similar for s2. Which causes my dates to be wrong. Both frmdt and frmdate should be 1 February 2012; but both are are Mon Jan 02 00:00:00 IST 2012. Similar for todt and todate.


Solution

  • Try this:

      String fs = "01/02/2012";
      String ts = "01/03/2013";
      DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
      sdf.setLenient(false);
      Date fdate = sdf.parse(fs);
      Date tdate = sdf.parse(ts);
      if (fdate.before(tdate) || f.date.equals(tdate)) {
             //process;      
      }
    

    You've got too much going on. It's much simpler.