java處理資料庫date類型資料__資料庫

來源:互聯網
上載者:User
1.使用Date類和TimeStamp類的valueOf轉換時間
  Date.valueOf();
  TimeStamp.valueOf();
  如果這兩種轉換直接用在sal語句上,那麼最外層要加雙引號或單引號的;比如插入時間:insert into value('Date.valueOf("2012-12-12")');


2、在資料庫中插入時間


PreparedStatement ps = con.prepareStatement("insert into TableName(dAddTime) values(?)");
這裡有三種方式:
1) ps.setDate(1,new java.sql.Date(System.currentTimemillis()));
2) ps.setTime(2,new java.sql.Time(System.currentTimemillis()));
3) ps.setTimestamp(3,new java.sql.Timestamp(System.currentTimemillis()));
第一種只插入年月日 0000-00-00
第二種只插入時間 00:00:00 
第三種則插入完整的時間 0000-00-00 00:00:00.000 .000是毫秒數。




3.java.sql.Date與java.util.Date類型轉換  
  
public static java.util.Date sqlDateToutilDate(java.sql.Date sdate)  
{  
    java.util.Date udate = null;  
    long t = sdate.getTime();  
    udate = new Date(t);  
    return udate;  
}  
public static java.sql.Date utilDateTosqlDate(java.util.Date udate)  
{  
    java.sql.Date sdate = null;  
    long t = udate.getTime();  
    sdate = new java.sql.Date(t);  
    return sdate;  
}  
  
public static void main(String[] args) {  
    
   Date date = new Date();  
   System.out.println("日期轉字串:" + ConvertDate.DateToStr(date));  
   System.out.println("字串轉日期:" + ConvertDate.StrToDate(ConvertDate.DateToStr(date)));  
    
}  


4.常見的java程式轉換
//String轉Date
   public static void dataTest() {
        SimpleDateFormat format = new SimpleDateFormat("2012-12-12 00:00:00");
        Date lastModifyTime;
        try {
            lastModifyTime = format.parse("2012-12-12 00:00:00");
            System.out.println(lastModifyTime.toLocaleString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


//Date轉String
    public static void testData() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            System.out.println(sdf.format("2012-12-12 01:12:11"));
            System.out.println(java.sql.Timestamp.valueOf("2012-12-12 01:12:11"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.