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

后端 未结 4 2059
耶瑟儿~
耶瑟儿~ 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:24

    Check out SimpleDateFormat. You can use this to both parse and format. I would suggest parsing the above into a Date object using one SimpleDateFormat, and then formatting to a String using a 2nd SimpleDateFormat.

    Note that SimpleDateFormat suffers from threading issues, and so if you're using this in a threaded environment, either create new SimpleDateFormats rather than used static versions, or use the corresponding but thread-safe classes in Joda.

    0 讨论(0)
  • 2021-01-16 17:29

    You can use SimpleDateFormat. Although there's no format specification for micro-seconds (the last fragment of your input), you can make use of the fact that the parser ignores the rest of the string if it has already managed to match the configured pattern:

    SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
    System.out.println(formatter.format(parser.parse("2009-10-27 14:36:59.580250")));
    

    The parser will in this case simply ignore the last part ":59.580250" of the input string.

    0 讨论(0)
  • 2021-01-16 17:37

    Keep in mind when you do this that you are losing precision. Depending on your specific application, this may or may not matter.

    If you already have the original date saved somewhere, this is not an issue. However, if the source date is from a transient source (e.g., streaming in from a physical sensor of some sort), it may be a good idea to persist the interim Date object (output of SimpleDateFormat#parse(String)) somewhere.

    Just thought I'd point that out.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题