1

I want to convert a string to date before storing it and I used

SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
Date returnDate = format.parse(date);

When I ran this with sample date: the input string for date conversion is 2014-05-06 the parsed date is Mon Jan 06 00:05:00 IST 2014

now when I store the returnDate in MySql the value is 2014-01-06 00:05:00

Why is the date changed ? Want to know if I am missing something. I went through the posts related to date string conversion : How to convert a date from a Datepicker to Mysql DATETIME format using java?

2

3 Answers 3

6

In your DateFormat use MM for month instead of mm, that is for minutes

Reference: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Sign up to request clarification or add additional context in comments.

Comments

2

java.time

Use only the modern java.time classes for your date-time handling. Never use the terribly-flawed legacy classes such as Date, Calendar, SimpleDateFormat, etc.

LocalDate

For a date-only value, without time-of-day, and without time zone, use java.time.LocalDate class.

ISO 8601

Your input string of YYYY-MM-DD complies with the ISO 8601 standard for date-time formats.

The java.time classes use the standard formats by default when parsing/generating text. So no need to specify a formatting pattern. The LocalDate class can parse directly.

LocalDate ld = LocalDate.parse ( "2014-05-06" ) ;

Generate the same standard text.

String output = ld.toString() ;

1 Comment

The OP has used the wrong symbol, m instead of M. I suggest you add a note about this problem to your answer. Also, since Java has different meanings of Y vs. y and D vs. d, I would avoid using Y and D where y and d is meant even when I point to a resource (e.g. ISO 8601) that uses the generic symbol. For learners: As this answer suggests, new code should use java.time API instead of the error-prone legacy java.util date-time API.
0

You can use like this :

Date mDate= new Date(System.currentTimeMillis());
        SimpleDateFormat mDateFormat= new SimpleDateFormat("dd MMM yyyy HH:mm a");
        String dateformat=mDateFormat.format(mDate);


the string ["dd MMM yyyy HH:mm a"]  can be changed according to need of formate.

Like in your case : "yyyy-mm-dd

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.