Search code examples
javajava-timelocaltimetime-formatseconds

LocalTime parse truncating time's second value


I have similar issue to this.There is no solution there and I am not working with JSON mapping.

LocalTime.parse on time string is removing second part. I have put the test code below. Any suggestion?

public class LocalTimeIssue {
  public static void main(String[] args) {
    Time someSQLTimeWithZero = new Time(1715264820000L); //09:27:00
    printTime(someSQLTimeWithZero); //09:27

    Time someSQLTimeWithNoZero = new Time(1715264821000L); //09:27:01
    printTime(someSQLTimeWithNoZero); //09:27:01
  }

  private static void printTime(Time someSQLTime) {
    String strTime = someSQLTime.toString();
    LocalTime someLocalTime = LocalTime.parse(strTime, DateTimeFormatter.ofPattern("HH:mm:ss"));
    System.out.println(someLocalTime);
  }
}

Solution

  • The seconds are not truncated - println(Object x) prints the stringified object:

    This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

    LocalTime.toString() uses the shortest possible format, as documented:

    The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

    If you want different formatting, use a formatter for the printed value:

    String strTime = someSQLTime.toString();
    DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
    LocalTime someLocalTime = LocalTime.parse(strTime, parseFormatter);
    
    DateTimeFormatter printFormatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
    System.out.println(printFormatter.format(someLocalTime));
    

    This examples prints:

    17:27:00.000
    17:27:01.000
    

    Edit: Transforming java.sql.Time to java.time.LocalTime can be simplified - converting to string and then parsing the string is not needed, the method Time.toLocalTime() does this exactly:

    Converts this Time object to a LocalTime. The conversion creates a LocalTime that represents the same hour, minute, and second time value as this Time.

    The transformation becomes this:

    LocalTime someLocalTime = someSQLTime.toLocalTime();