Search code examples
javadatetimedatetime-formatsqldatetime

2017-01-01 00:08:57.231 format equals yyyy-MM-dd.HH:mm:ss?


I'm a bit baffled what format these timestamps are in. I was told the format to use is yyyy-MM-dd.HH:mm:ss but all of the timestamps appear like this 2017-01-01 00:08:57.231, 2017-01-01 07:43:36.348, or 2017-01-01 13:25:55.683. I'm not understanding why there are four sections to the time ?:Hour:Minute:Second in the actual data I have when the format I'm supposed to be using only has three time sections. Are these datetime timestamps not actually in the format of yyyy-MM-dd.HH:mm:ss?


Solution

  • No, your suspicion is correct, your example date-time strings are not in the format yyyy-MM-dd.HH:mm:ss. The dot between dd and HH must be a simple mistake, it should be a space since there is a space between date and time in the timestamp strings. Furthermore all of your example strings include milliseconds: in 00:08:57.231 you’ve got 57 seconds and 231 milliseconds, or if you like, 57.231 seconds, so the last section may also be referred to as fraction of second.

        DateTimeFormatter formatter
                = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
        String timestampString = "2017-01-01 00:08:57.231";
        LocalDateTime dateTime = LocalDateTime.parse(timestampString, formatter);
        System.out.println(dateTime);
    

    Output:

    2017-01-01T00:08:57.231

    For the nerdily curious: It is possible to parse the string, or more precisely most of it, with the format you had been given, only correcting the dot into a space:

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String timestampString = "2017-01-01 00:08:57.231";
        LocalDateTime dateTime = LocalDateTime.from(
                formatter.parse(timestampString, new ParsePosition(0)));
    

    In this case the result comes without the milliseconds:

    2017-01-01T00:08:57

    I see no reason why you should want this, though.

    Avoid SimpleDateFormat

    In a comment you gave a snippet that uses the SimpleDateFormat class. This class is not only long outdated, it is also notoriously troublesome. I see no reason why you should want to use it. Instead I am using java.time, the modern Java date and time API. In my experience it is so much nicer to work with.

    Links

    Oracle tutorial: Date Time explaining how to use java.time. You may especially want to study the section Parsing and Formatting.