Java 中插入 Timestamp 数据
在 Java 中插入 Timestamp 数据到数据库通常涉及以下几个步骤:

创建 Timestamp 对象
import java.sql.Timestamp; import java.util.Date; // 方法1:使用当前时间 Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // 方法2:从 Date 对象创建 Date date = new Date(); Timestamp timestamp = new Timestamp(date.getTime()); // 方法3:指定特定时间 Timestamp timestamp = new Timestamp(2025, 5, 15, 10, 30, 0, 0); // 注意:月份从0开始
使用 JDBC 插入到数据库
使用 PreparedStatement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class TimestampExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "username";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String sql = "INSERT INTO your_table (name, created_at) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, "Example Record");
pstmt.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
System.out.println("Record inserted successfully!");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 JPA/Hibernate
import javax.persistence.*;
import java.sql.Timestamp;
@Entity
@Table(name = "your_table")
public class YourEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Column(name = "created_at")
private Timestamp createdAt;
// 构造函数、getter和setter
}
注意事项
- 月份索引:在 Java 中,月份是从 0 开始的(0=一月,11=十二月)
- 时区处理:Timestamp 不存储时区信息,如果需要处理时区,考虑使用
java.time包中的类 - 数据库兼容性:不同数据库对 Timestamp 的处理可能略有不同
- 精度问题:Timestamp 可以精确到纳秒,但数据库可能不支持这么高的精度
使用 Java 8 的 java.time API(推荐)
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
// 从 LocalDateTime 转换为 Timestamp
LocalDateTime now = LocalDateTime.now();
Timestamp timestamp = Timestamp.valueOf(now);
// 从 Timestamp 转换为 LocalDateTime
LocalDateTime localDateTime = timestamp.toLocalDateTime();
// 处理时区
LocalDateTime utcNow = LocalDateTime.now(ZoneId.of("UTC"));
Timestamp utcTimestamp = Timestamp.valueOf(utcNow);
使用 Java 8 的 java.time API 是更现代和推荐的方式,它提供了更清晰的 API 和更好的时区处理能力。

