Change date format in a Java string

Use LocalDateTime#parse() (or ZonedDateTime#parse() if the string happens to contain a time zone part) to parse a String in a certain pattern into a LocalDateTime.

String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));

Use LocalDateTime#format() (or ZonedDateTime#format()) to format a LocalDateTime into a String in a certain pattern.

String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18

Or, when you’re not on Java 8 yet, use SimpleDateFormat#parse() to parse a String in a certain pattern into a Date.

String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);

Use SimpleDateFormat#format() to format a Date into a String in a certain pattern.

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18

See also:

  • Java string to date conversion

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 example M for months and m for minutes. Also, years exist of four digits yyyy, not five yyyyy. Look closer at the code snippets I posted here above.

Leave a Comment