Parse time with microseconds in Java

后端 未结 3 334
情深已故
情深已故 2021-01-19 02:40

I am having problems parsing time strings in Java that are in the format of 2013-01-09 09:15:03.000000. In my data, the last three digits are always 0 (meaning

相关标签:
3条回答
  • 2021-01-19 03:00

    try java.sql.Timestamp

         Timestamp ts = Timestamp.valueOf("2013-01-09 09:15:03.500000"); 
         Date date = new Date(ts.getTime())
    

    it's also thread-safe and fast as opposed to SimpleDateFormat

    0 讨论(0)
  • 2021-01-19 03:01

    I've figured out myself. Just FYI, Apache commons' FastDateFormat seems accepting the SSS000 format and parses the time correctly.

    0 讨论(0)
  • 2021-01-19 03:01

    java.time

    I should like to contribute the modern answer. Use java.time, the modern Java date and time API. One option, you may use a formatter:

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSS");
        LocalDateTime dateTime = LocalDateTime.parse(timeString, formatter);
        System.out.println(dateTime);
    

    When using the string from your question, "2013-01-09 09:15:02.500000", this printed:

    2013-01-09T09:15:02.500
    

    If you want the value printed with six decimals on the seconds even when the last three decimals are 0, use the same formatter to format the time back into a string:

        System.out.println(dateTime.format(formatter));
    

    The other option, you may exploit the fact that your string resembles the ISO 8601 format, the format that the modern classes parse as their default, that is, without any explicit formatter. Only ISO 8601 has a T to denote the start of the time part, but we can fix that easily:

        LocalDateTime dateTime = LocalDateTime.parse(timeString.replace(' ', 'T'));
    

    It gives the same result, 2013-01-09T09:15:02.500. It’s shorter, but also more tricky.

    Why bother?

    The classes Date and Timestamp are long outdated, and SimpleDateFormat in particular has proven troublesome. Its surprising behaviour in your situation is just one little story out of very many. The modern API is generally so much nicer to work with.

    Why didn’t your formatter work?

    While the format pattern strings used by SimpleDateFormat and DateTimeFormatter are similar, there are differences. One is that SimpleDateFormat understands uppercase S as milliseconds no matter of there are one or nine of them, whereas to DateTimeFormatter they mean fraction of second. Your SimpleDateFormat furthermore grabbed all six digits after the decimal point, ignoring the fact that you had typed only three S, so there were no zeroes left to match the '000' (by the way, the apostrophes are not necessary, only letters need them).

    Link

    Oracle Tutorial

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