I've a String
representing a date.
String date_s = "2011-01-18 00:00:00.0";
I'd like to convert it to a Date
and output it in YYYY-MM-DD
format.
2011-01-18
How can I achieve this?
Okay, based on the answers I retrieved below, here's something I've tried:
String date_s = " 2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));
But it outputs 02011-00-1
instead of the desired 2011-01-18
. What am I doing wrong?
The answer is of course to create a SimpleDateFormat object and use it to parse Strings to Date and to format Dates to Strings. If you've tried SimpleDateFormat and it didn't work, then please show your code and any errors you may receive.
Addendum: "mm" in the format String is not the same as "MM". Use MM for months and mm for minutes. Also, yyyyy is not the same as yyyy. e.g.,:
Other answers are correct, basically you had the wrong number of "y" characters in your pattern.
Time Zone
One more problem though… You did not address time zones. If you intended UTC, then you should have said so. If not, the answers are not complete. If all you want is the date portion without the time, then no issue. But if you do further work that may involve time, then you should be specifying a time zone.
Joda-Time
Here is the same kind of code but using the third-party open-source Joda-Time 2.3 library
When run…
Using the
java.time
package in Java 8 and later: