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?
Best Answer
Use
LocalDateTime#parse()
(orZonedDateTime#parse()
if the string happens to contain a time zone part) to parse aString
in a certain pattern into aLocalDateTime
.Use
LocalDateTime#format()
(orZonedDateTime#format()
) to format aLocalDateTime
into aString
in a certain pattern.Or, when you're not on Java 8 yet, use
SimpleDateFormat#parse()
to parse aString
in a certain pattern into aDate
.Use
SimpleDateFormat#format()
to format aDate
into aString
in a certain pattern.See also:
Update: as per your failed attempt: the patterns are case sensitive. Read the
java.text.SimpleDateFormat
javadoc what the individual parts stands for. So stands for exampleM
for months andm
for minutes. Also, years exist of four digitsyyyy
, not fiveyyyyy
. Look closer at the code snippets I posted here above.