>我正在尝试将格式为" 01/02/2018 02:48:04 PM"的字符串转换为小日期时间格式以插入MS SQL。
import java.sql.Date;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class TimeStampTest {
public static void main(String[] args) {
String originalDate ="01/02/2018 02:29:23 PM";
System.out.println(convertToSmallDatetimeFormat(originalDate));
}
private static Timestamp convertToSmallDatetimeFormat(String originalDate) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MM/dd/yyyy hh:mm:ss a")
.toFormatter(Locale.US);
LocalDateTime localDate = LocalDateTime.parse(originalDate,formatter);
return new Timestamp(localDate.getNano()/1000000);
}
}
但是当我执行以下代码时,我意识到
LocalDateTime localDate = LocalDateTime.parse(originalDate,formatter);
我得到一些垃圾值 2018-01-02T15:58:04
这导致 localDate.getNano() 为 0
您可以使用Timestamp.valueOf
private static Timestamp convertToSmallDatetimeFormat(String originalDate) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MM/dd/yyyy hh:mm:ss a")
.toFormatter(Locale.US);
LocalDateTime localDate = LocalDateTime.parse(originalDate,formatter);
System.out.println("****"+localDate);
return Timestamp.valueOf(localDate);
}
要转换字符串并将其插入smalldatetime
您根本不需要使用java.sql.Timestamp
。只需将LocalDateTime
对象传递给PreparedStatement#setObject
,如下所示:
Statement st = conn.createStatement();
st.execute("CREATE TABLE #tmp (id int PRIMARY KEY, sdt smalldatetime)");
PreparedStatement ps = conn.prepareStatement("INSERT INTO #tmp (id, sdt) VALUES (?, ?)");
ps.setInt(1, 1);
String originalDate = "01/02/2018 02:29:43 PM";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MM/dd/yyyy hh:mm:ss a")
.toFormatter(Locale.US);
LocalDateTime ldt = LocalDateTime.parse(originalDate, formatter);
System.out.println(ldt); // 2018-01-02T14:29:43
ps.setObject(2, ldt);
ps.executeUpdate();
而且,如果您使用的是 mssql-jdbc 版本 7.1.0 或更高版本,则可以将值直接检索到LocalDateTime
对象中(我为该功能创建了拉取请求)
ResultSet rs = st.executeQuery("SELECT sdt FROM #tmp WHERE id=1");
rs.next();
LocalDateTime retrieved = rs.getObject(1, LocalDateTime.class);
System.out.println(retrieved); // 2018-01-02T14:30
// note that the minutes value is rounded
您实际上可以从MySQL查询本身执行此操作,这可能会节省一些时间:
根据您使用的版本,这适用于MariaDB
SELECT DATE_FORMAT(date, "%Y-%m-%d %H:%M:%S") date FROM `table`