1

我正在尝试将格式为“01/02/2018 02:48:04 PM”的字符串转换为 smalldatetime 格式以插入 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

4

3 回答 3

0

转换字符串并将其插入,因为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
于 2019-04-22T01:46:23.760 回答
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);
}
于 2019-04-19T03:39:49.533 回答
-1

您实际上可以从 MySQL 查询本身执行此操作,这可能会为您节省一些时间:

根据您使用的版本,这适用于 MariaDB

SELECT DATE_FORMAT(date, "%Y-%m-%d  %H:%M:%S") date FROM `table`
于 2019-04-19T03:32:17.693 回答