如何在 JDBC 程序中将时间戳对象转换为日期?
jdbcjava 8object oriented programmingprogramming
Timestamp 类的 getTime() 方法从纪元时间 1,1970 00:00:00.000 GMT 检索并返回当前时间戳(以毫秒为单位,长整型)的时间。
Timestamp timestamp = rs.getTimestamp("DispatTimestamp"); long time = timestamp.getTime();
java.sql.Date 类的构造函数接受一个 long 变量,该变量表示从纪元时间开始的毫秒数,并构造 date 对象。
//打印调度日期 System.out.println("Date of dispatch: "+new Date(time));
使用这些,您可以在 JDBC 中将 TimeStamp 对象转换为 Date 对象。
假设我们已经与 MySQL 数据库建立了连接,并使用语句对象创建了一个名为 dispatch_data 的表,如下所示:
//创建 Statement 对象 Statement stmt = con.createStatement(); //查询以创建表 String create_query = "Create table disptach_data (" + "Product_Name VARCHAR(255), " + "Name_Of_Customer VARCHAR(255) , " + "Dispatch_Timestamp timestamp, " + "Location VARCHAR(255) )"; stmt.execute(create_query);
我们使用 PreparedStatement 填充了表格,如下所示:
String query = "INSERT INTO dispatch_data VALUES (?, ?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "KeyBoard"); pstmt.setString(2, "Amith"); pstmt.setTimestamp(3, new Timestamp(1567296000000L)); pstmt.setString(4, "Hyderabad"); pstmt.execute(); pstmt.setString(1, "Earphones"); pstmt.setString(2, "Sumith"); pstmt.setTimestamp(3, new Timestamp(1556668800000L)); pstmt.setString(4, "Vishakhapatnam"); pstmt.execute(); pstmt.setString(1, "Mouse"); pstmt.setString(2, "Sudha"); pstmt.setTimestamp(3, new Timestamp(1551398399000L)); pstmt.setString(4, "Vijayawada"); pstmt.execute(); System.out.println("Records inserted......");
以下 JDBC 程序从 ResultSet 中检索时间戳值并将其转换为日期和时间对象并打印详细信息。
import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; public class TimeStampToDate { public static void main(String args[])throws Exception { //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获取连接 String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建 Statement 对象 Statement stmt = con.createStatement(); //创建 Statement 对象 stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from dispatch_data"); //检索值 while(rs.next()) { System.out.println("Product Name: "+rs.getString("Product_Name")); System.out.println("Name Of The Customer: "+rs.getString("Name_Of_Customer")); //检索时间戳 Timestamp timestamp = rs.getTimestamp("Dispatch_Timestamp"); //打印发货日期 System.out.println("Date of dispatch: "+new Date(timestamp.getTime())); //打印发货时间 System.out.println("Time Of Dispatch: "+new Time(timestamp.getTime())); System.out.println(); } } }
输出
Connection established...... Product Name: KeyBoard Name Of The Customer: Amith Date of dispatch: 2019-09-01 Time Of Dispatch: 05:30:00 Product Name: Ear phones Name Of The Customer: Sumith Date of dispatch: 2019-05-01 Time Of Dispatch: 05:30:00 Product Name: Mouse Name Of The Customer: Sudha Date of dispatch: 2019-03-01 Time Of Dispatch: 05:29:59