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
  • 520
  • 2
  • 10
  • 32
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

52

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
  • 389,931
  • 88
  • 552
  • 692
9

mm stands for "minutes". Use MM instead:

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
NPE
  • 464,258
  • 100
  • 912
  • 987
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
  • 9,842
  • 2
  • 62
  • 47
4

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
  • 7,831
  • 4
  • 23
  • 39
Zeeshan Akhter
  • 1,851
  • 19
  • 19
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,340
  • 8
  • 31
  • 45