String date_s = "2011-01-18 00:00:00.0"; I want to change these strings from Java to Date and print them out in YYYY_MM_DD format, but what should I do?
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));
I tried it like this, but it doesn't print as 2011-01-18 and it says 02011-00-1
java date
SimpleDateFormat#parse() replaces the String with the date type, as shown in the example below.
String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);
impleDateFormat#format() is a Date format that puts a value in the String.
String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18
And if you read JavaDoc's Simple Date Format, M stands for the moon and m stands for minutes. Also, year is not five digits like yyyy, but four digits.
© 2024 OneMinuteCode. All rights reserved.