例如,我有一個表,如下所示:如何使用PostgreSQL數據庫插入當前日期和時間並以特定格式恢復它?
CREATE TABLE MESSAGES(
MESSAGE_ID INTEGER PRIMARY KEY,
SENT TIMESTAMP NOT NULL
);
雖然我的java類我已MESSAGE_ID爲整數,並將其作爲日曆。
我的查詢是這樣的:
同時插入(只是顯示的日期部分):
String sql1="insert into messages (message_id,sent) values (?,?)";
Calendar cal=Calendar.getInstance();
ps1.setDate(2, new java.sql.Date(cal.getTimeInMillis()));
插入表視圖後是:
MESSAGE_ID發送
1 | 2016-12-22 00:00:00
2 | 2016-6-22 00:00:00
在檢索(只是顯示的日期部分):
String sql="select message_id, sent from messages";
Messages msg=new Messages();
Calendar cal=Calendar.getInstance();
Date d=rs.getDate("sent");
String pattern = "yyyy-MM-dd hh:mm:ss a";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String conDate=simpleDateFormat.format(d);
我得到的日期,但時間總是12:00:00 AM。 我想表明得到它在這樣的格式:
難道我做錯任何事「的消息是在2016年12月3日下午19:30:00發送」?任何類型的幫助表示讚賞...... :)
'hh'是上午/下午你想要的時間'HH':http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html –
我讀的方式[使用Java 8日期和時間類](https://jdbc.postgresql.org/documentation/head/8-date-time.html),如果您可以使用'java.time'類和最新的PostgrSQL JDBC驅動程序,你應該傳遞一個'LocalDateTime'到你準備好的語句,並要求從結果集中返回一個'LocalDateTime'。這是個好消息,因爲這些類比'Date'和'SimpleDateFormat'要好得多。 –