
java 如何存 timestamp
用户关注问题
Java 中如何将时间转换为 Timestamp 类型?
我想把当前时间转换成 Java 的 Timestamp 类型,应该怎么做?
使用 Java 的 Timestamp 类转换时间
可以通过 java.sql.Timestamp 类将 java.util.Date 或 System.currentTimeMillis() 获取的时间转换为 Timestamp。例如:
long currentTimeMillis = System.currentTimeMillis();
Timestamp timestamp = new Timestamp(currentTimeMillis);
或者直接使用 Date 对象:
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
如何在 Java 中将 Timestamp 存储到数据库?
我想把 Timestamp 类型的数据写入数据库,应该采用什么方式?
通过 PreparedStatement 设置 Timestamp 参数
使用 JDBC PreparedStatement 时,可以调用 setTimestamp 方法来存储 Timestamp 类型的数据。示例:
PreparedStatement pstmt = connection.prepareStatement("INSERT INTO table_name (time_column) VALUES (?)");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
pstmt.setTimestamp(1, timestamp);
pstmt.executeUpdate();
Java 8+ 中处理时间戳有什么更好的方式?
有没有比 java.sql.Timestamp 更现代的方式处理时间戳?
推荐使用 java.time 包中的 Instant 和 LocalDateTime
Java 8 以后,建议使用 java.time 包处理时间相关操作。时间戳通常用 Instant 表示。示例:
Instant instant = Instant.now();
Timestamp timestamp = Timestamp.from(instant);
也可以将 Timestamp 转换为 Instant:
Instant instant = timestamp.toInstant();
这种方式更加灵活且线程安全。