java - 如何将 "01/30/2018 02:29:23 PM"转换为smalldatetime格式?我在我的应用程序中使用 MSSQL,并且该列是smalldatetime 格式

标签 java jdbc timestamp java.util.date smalldatetime

我正在尝试将格式为“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

最佳答案

您可以使用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);
}

关于java - 如何将 "01/30/2018 02:29:23 PM"转换为smalldatetime格式?我在我的应用程序中使用 MSSQL,并且该列是smalldatetime 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55756089/

相关文章:

java - 使用servlet和html在服务器上上传文件时找不到符号getServletContext()错误

java - 按表从 ResultSet 中删除列

java - 同步Web服务方法有意义吗?

Java/JDBC/MySQL : How do I troubleshoot why DriverManager. getConnection() 返回 NULL?

Eclipse 中的 java.lang.ClassNotFoundException : com. mysql.jdbc.Driver

python - 如何将API时间戳转换为python日期时间对象

java - 如何访问Java LinkedList节点的私有(private)字段?

java - JDBC未插入int jdbc表

MySQL 日期时间与时间戳关于如何记录/显示时间

c - 下面的c程序有什么错误?