java.time
其他的答案使用传统的日期时间类,现在建到Java 8和后来的java.time框架所取代。
首先解析日期部分。
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("mm-DD-yyyy");
LocalDate localDate = LocalDate.parse("22-May-2014" , dateFormatter);
二,解析时间部分。
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("h:m");
LocalTime localTime = LocalTime.parse("7:20" , dateFormatter);
三,确定这个值有什么意义的时区。这是蒙特利尔时间,巴黎时间还是加尔各答时间?
ZoneId zoneId = ZoneId.of("America/Montreal");
组合成ZonedDateTime
。
ZonedDateTime zdt = ZonedDateTime.of(localDate , localTime , zoneId);
您可以到这个ZonedDateTime
通过setObject
方法上PreparedStatement
与JDBC 4.2兼容的驱动传递到你的数据库。但如果不是,则转换为旧的java.sql.Timestamp
类型。那个老班级有一个方便转换的新方法,它需要一个Instant
对象。 Instant
是UTC时间轴上的一个时刻,分辨率为纳秒。我们可以从我们的ZonedDateTime
中提取Instant
。
Instant instant = zdt.toInstant();
java.sql.Timestamp ts = java.sql.Timestamp.from(instant);
在您的PreparedStatement
,请致电setTimestamp
。