![](/img/trans.png)
[英]How to map java.time.LocalTime with milliseconds to a java.sql.Time with miliseconds
[英]Converting java.time.LocalTime to java.sql.Time
我目前在這些代碼行中拋出IllegalArgumentException
:
Time timeIn = Time.valueOf( res.getCheckInTime().toString());
Time timeOut = Time.valueOf( res.getCheckOutTime().toString());
arguments 都是LocalTime
存儲本地時間,例如11:05
:
res.getCheckInTime()
res.getCheckOutTime()
有誰可以幫我離開這里嗎?
Java 文檔:
public static Time valueOf(String s)
將 JDBC 時間轉義格式的字符串轉換為時間值。
Parameters: s - time in format "hh:mm:ss" Returns: a corresponding Time object
唯一接受的格式是hh:mm:ss
為什么需要使用res.getCheckInTime().toString()
? 不能使用Time.valueOf(LocalTime s)
方法嗎?
請參見以下示例:
public static void main(String[] args) {
LocalTime checkInTime = LocalTime.now();
LocalTime checkOutTime = LocalTime.now().plusHours(12);
Time timeIn = Time.valueOf(checkInTime);
Time timeOut = Time.valueOf(checkOutTime);
System.out.println("timeIn => " + timeIn);
System.out.println("timeOut => " + timeOut);
}
將參數傳遞給工廠方法java.sql.Time.valueOf()
時,它應該可以工作:
String("11:05:00")
(最多秒)java.time.LocalTime
。 public static void main(String[] args) throws java.lang.Exception {
Reservation res = new Reservation("11:05", "18:05");
System.out.println(res);
Time timeIn = Time.valueOf("11:05:00");
System.out.printf("toString returns '11:05:00' as expected? %s\n", "11:05:00".equals(res.getCheckInTime()));
Time timeOut = Time.valueOf(res.getCheckOutTime());
System.out.println("sql.Time in: " + timeIn + " , out: " + timeOut);
}
static class Reservation {
LocalTime checkIn;
LocalTime checkOut;
public Reservation(String in, String out) {
this.checkIn = LocalTime.parse(in);
this.checkOut = LocalTime.parse(out);
}
public LocalTime getCheckInTime() {
return checkIn;
}
public LocalTime getCheckOutTime() {
return checkOut;
}
public String toString() {
return String.format("Reservation {checkIn: %s, checkOut: %s}", getCheckInTime(), getCheckOutTime());
}
}
在 IDEone 上嘗試可運行的演示。 也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.