我有与this类似的问题。那里没有解决方案,而且我不使用 JSON 映射。
LocalTime.parse 时间字符串正在删除第二部分。我已将测试代码放在下面。有什么建议吗?
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);
}
}
println(Object x)
打印字符串化对象:
此方法首先调用 String.valueOf(x) 来获取打印对象的字符串值,然后其行为就好像调用 print(String),然后调用 println()。
LocalTime.toString()
使用尽可能短的格式,如文档所示:
使用的格式将是输出时间的完整值的最短格式,其中省略的部分隐含为零。
如果您想要不同的格式,请使用格式化程序来打印值:
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));
此示例打印:
17:27:00.000
17:27:01.000
编辑: 将
java.sql.Time
转换为java.time.LocalTime
可以简化,不需要转换为字符串然后解析字符串。方法 Time.toLocalTime()
正是这样做的:
将此 Time 对象转换为 LocalTime。该转换创建一个 LocalTime,它表示与此 Time 相同的小时、分钟和秒时间值。
改造后就变成这样了:
LocalTime someLocalTime = someSQLTime.toLocalTime();