How to convert a date String into the right format in Java?

后端 未结 4 2111
耶瑟儿~
耶瑟儿~ 2021-01-16 16:43

Can somebody please explain to me how I can convert

2009-10-27 14:36:59.580250

into

27.10.2009, 14:36 ?

Th

4条回答
  •  情书的邮戳
    2021-01-16 17:42

    You can use java.text.SimpleDateFormat for this. First step is to parse the first string into a java.util.Date object using SimpleDateFormat based on the pattern of the first string. Next step is to format the obtained java.util.Date object into a string based on the pattern of the second string. For example:

    String datestring1 = "2009-10-27 14:36:59.580250";
    Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(datestring1);
    String datestring2 = new SimpleDateFormat("dd.MM.yyyy HH:mm").format(date1);
    System.out.println(datestring2);
    

    Edit: I've removed the .SSSSSS part from the first pattern because it failed. But in my opinion it should in theory have worked with "yyyy-MM-dd HH:mm:ss.SSS" and "yyyy-MM-dd HH:mm:ss.SSSSSS" as well, but it is calculating them as seconds! I consider this as a buggy implementation in SimpleDateFormat. The JodaTime handles the millis/micros perfectly with those patterns.

提交回复
热议问题