1. 程式人生 > >關於向資料庫中新增日期

關於向資料庫中新增日期

寫了java程式碼連線資料庫,在向資料庫中新增日期的時候遇到問題
比如向資料庫中新增日期為Date date = new Date(2016, 9, 21),但是在資料庫中日期就會變為3916-10-21,連續添加了幾次,發現每次新增的日期年都會加1900,月份會加1,日不變。
檢視Date原始碼發現:
Date為 java.sql.Date;

 public String toString () {
        int year = super.getYear() + 1900;
        int month = super.getMonth() + 1;
        int day
= super.getDate(); char buf[] = "2000-00-00".toCharArray(); buf[0] = Character.forDigit(year/1000,10); buf[1] = Character.forDigit((year/100)%10,10); buf[2] = Character.forDigit((year/10)%10,10); buf[3] = Character.forDigit(year%10,10); buf[5] = Character.forDigit(month/10,10); buf[6
] = Character.forDigit(month%10,10); buf[8] = Character.forDigit(day/10,10); buf[9] = Character.forDigit(day%10,10); return new String(buf); }

發現在toString ()方法中,年份後面添加了1900,月份後面添加了1

所以我在新增日期的時候改為:
Date date = new Date(2016-1900, 9-1, 21)
或者
在API中發現Date類中有個方法
**static Date valueOf(String s)
將 JDBC 日期轉義形式的字串轉換成 Date 值。**
所以可以改為
**Date date = new Date(2016, 9, 21);
date.valueOf(“2016-9-22”);**