0

I take in the date from the html field as date/month/year. If the input is :

01/07/2013

the date in the mysql database goes as 2013-08-01. Thus the month gets incremented by one. Why is that ?

Following snippet inserts the date to the DB from html field.

        String dateMonthYear[] = issueDate.split("/");

        System.out.println("DATE MONT YEAR-------> "+dateMonthYear[1]);
        // PRINTS THE CORRECT MONTH

        Calendar cal = Calendar.getInstance();

        cal.set(Calendar.YEAR, Integer.parseInt(dateMonthYear[2]));
        cal.set(Calendar.MONTH, Integer.parseInt(dateMonthYear[1]));
        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateMonthYear[0]));
        Date issueDateDB = cal.getTime();

        issued.setDateOfIssue(issueDateDB);

        // commit operation

The type of the corresponding type in the db is Date . What could be the reason that moth gets incremented by one ?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

3 Answers3

2

This is because Calendar.MONTH is 0-based (Calendar.JANUARY = 0, and so on). Add 1 to the month part when writing to the database, substract 1 when reading from it.

I recommend reading this very good answer to a similar question.

Community
  • 1
  • 1
RandomSeed
  • 29,301
  • 6
  • 52
  • 87
  • 1
    but you see..`issuedDateDB.getTime` prints `Jul 1, 2013 12:42:51 PM` and not `Aug 1,2013`. Why is it so ? – Suhail Gupta Jul 01 '13 at 07:20
  • But you see, you're set'ting a value of 1..12, but the API is expecting a value of 0..11. RandomSeed is correct. And Shreyansh Jogi is suggesting a different ... perhaps better ... approach of using SimpleDateFormat().parse(). – paulsm4 Jul 01 '13 at 07:25
  • @paulsm4 _"..you're set'ting a value of 1..12, but the API is expecting a value of 0..11.."_ I didn't get you. The point is just before inserting the date to the db,the month is `july` ! – Suhail Gupta Jul 01 '13 at 07:40
  • @SuhailGupta That's interesting... What is the output of just `Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, 1); System.out.println(cal.getTime());` ? Here I get "Fri **Feb** 01 (...)". – RandomSeed Jul 01 '13 at 08:22
  • @RandomSeed same..`Fri Feb 01 13:55:17 IST 2013` – Suhail Gupta Jul 01 '13 at 08:25
  • @SuhailGupta Then you must be initialising your `cal` variable in a different way. I executed your code snippet with `issueDate = "01/07/2013"` and `cal.getTime()` returns "Thu **Aug** 01 (...)". – RandomSeed Jul 01 '13 at 08:31
1
Date d = new SimpleDateFormat("dd/MM/yyyy").parse("01/07/2013");

try this instead

shreyansh jogi
  • 2,082
  • 12
  • 20
0

Just because calender's month starts with 0 not from 1 ex:- for january value of month is 0 not 1 .so you have to decrease month by -1.

Amit Gupta
  • 131
  • 11