0

I searched this issue but found only changing from String to Date and then displaying Date to String. I have a requirement, where I receive Date in String format and then I have to parse that in Date object and enter in Database.But whenever I convert String to Date it gives me wrong output. Please suggest. thanks in advance.

String subscribedDate="2012-09-28 11:00:00";
String oldFormat = "yyyy-mm-dd hh:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
Date dates=sdf1.parse(subscribedDate);
System.out.println(dates);
//code for entering dates in database. 

Output: Sat Jan 28 00:09:00 GMT 2012 (Which is incorrect!!). I want as 2012-09-28 11:00:00

0

5 Answers 5

6

Your format string is wrong. yyyy-mm-dd hh:mm:ss is basically saying "years-miniutes-days hours:minutes:seconds" which I'm pretty sure you don't want.

You want

String oldFormat = "yyyy-MM-dd hh:mm:ss";

Have a look at the SimpleDateFormat docs for more info

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

Comments

3

Firstly, the month field is represented using MM and not mm which is for minutes.

Secondly, the formatter can be used to print the date in the desired format.

String subscribedDate="2012-09-28 11:00:00";
String oldFormat = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
Date dates=sdf1.parse(subscribedDate);
System.out.println(sdf1.format(dates));
// code for entering dates in database. 

Comments

1

I suppose the oldFormat variable in the second line should be

oldFormat = "yyyy-MM-dd HH:mm:ss"; // hours counted 0~23

or

oldFormat = "yyyy-MM-dd hh:mm:ss"; // hours counted 0~11

Comments

1

Try to change oldFormat to

String oldFormat = "yyyy-MM-dd hh:mm:ss";

where MM are capital letters.

Comments

0

Try this:

        String oldFormat = "yyyy-MM-dd hh:mm:ss";

See the docs to find out why.

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.