fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. import java.time.LocalDate;
  8. import java.time.LocalDateTime;
  9. import java.time.format.DateTimeFormatter;
  10. import java.time.format.DateTimeFormatterBuilder;
  11. import java.util.Locale;
  12.  
  13. /* Name of the class has to be "Main" only if the class is public. */
  14. class Ideone
  15. {
  16. public static void main (String[] args) throws java.lang.Exception
  17. {
  18. String dateString = "2018-03-20 09:31:31";
  19.  
  20. DateTimeFormatter formatterForWrongFormat = new DateTimeFormatterBuilder()
  21. .append(DateTimeFormatter.ISO_LOCAL_DATE)
  22. .appendLiteral(" ")
  23. .append(DateTimeFormatter.ISO_LOCAL_TIME)
  24. .toFormatter();
  25.  
  26. //1- from String(wrong format) into datetime object
  27. LocalDateTime dateTime = LocalDateTime.parse(dateString , formatterForWrongFormat);
  28.  
  29. // 1.1 extract date object (Optional)
  30. LocalDate myDate = dateTime.toLocalDate();
  31.  
  32. // 2- now from your LocalDateTime to the String in the RIGHT format
  33. DateTimeFormatter formatterForRightFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a",
  34. Locale.ENGLISH);
  35.  
  36. System.out.println("right format: "+dateTime.format(formatterForRightFormat));
  37.  
  38. }
  39. }
Success #stdin #stdout 0.24s 35372KB
stdin
Standard input is empty
stdout
right format: 03/20/2018 09:31:31 AM