Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Conversion from String to sql Date in Java giving different output? [duplicate]

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?

like image 752
Mr.Chowdary Avatar asked May 02 '12 12:05

Mr.Chowdary


People also ask

Can we convert String to Date in java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.

How does sql compare dates in java?

Convert all sql types to Joda equivalents at the persistence layer and then work with Joda objects in your business logic. You won't regret it, believe me. LocalTime is probably the object you want to use then you can use compareTo() , isAfter() , isBefore() .

What is the correct way for converting a String to a Date?

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale. ENGLISH); String dateInString = "7-Jun-2013"; Date date = formatter. parse(dateInString); In the above example, we first need to construct a SimpleDateFormat object by passing the pattern describing the date and time format.


1 Answers

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.

like image 55
Bohemian Avatar answered Sep 28 '22 13:09

Bohemian