30

I have a string form of Date. I have to change it to Sql Date. so for that i have used the following code.

String startDate="01-02-2013";
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date date = sdf1.parse(startDate);
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());  

when i used the above code and run that. I got the following output.

2013-01-01.  

Here Month is not converted correctly.
Please tell me where is the problem and provide sample code to get correct result?

ZioN
  • 550
  • 2
  • 11
  • 35
Mr.Chowdary
  • 517
  • 1
  • 6
  • 18
  • I recommend you don’t use `SimpleDateFormat` and the two `Date` classes. Those classes are poorly designed and long outdated, the first in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Oct 27 '19 at 11:18

5 Answers5

53

mm is minutes. You want MM for months:

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");

Don't feel bad - this exact mistake comes up a lot.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
9

mm stands for "minutes". Use MM instead:

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
NPE
  • 486,780
  • 108
  • 951
  • 1,012
5

That is the simple way of converting string into util date and sql date

String startDate="12-31-2014";
SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yyyy");
java.util.Date date = sdf1.parse(startDate);
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime()); 
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
Zeeshan Akhter
  • 1,881
  • 20
  • 19
5

You need to use MM as mm stands for minutes.

There are two ways of producing month pattern.

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); //outputs month in numeric way, 2013-02-01

SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); // Outputs months as follows, 2013-Feb-01

Full coding snippet:

        String startDate="01-Feb-2013"; // Input String
        SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
        java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
        java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
        System.out.println(sqlStartDate); // Outputs : 2013-02-01
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
1

While using the date formats, you may want to keep in mind to always use MM for months and mm for minutes. That should resolve your problem.

juzraai
  • 5,693
  • 8
  • 33
  • 47