簡體   English   中英

獲取當前日期並將其保存在數據庫中

[英]Getting current Date and saving it in database

如何獲取yyyy-MM-dd格式的當前日期並將其保存在帶有Date值的數據庫中? 我有此代碼,但它不起作用...

Java:

Calendar cal = Calendar.getInstance(); 
java.util.Date d = new java.util.Date();
d.setMonth(cal.get(Calendar.MONTH));
d.setDate(cal.get(Calendar.DATE)-1900);
d.setYear(cal.get(Calendar.YEAR));

這是我的PreparedStatement:

pstmt.setDate(6, (Date)d);

您必須使用java.sql.Date實例設置為數據庫列。

java.util.Date實例轉換為java.sql.Date

您還可以使用Calander實例進行轉換。

變更

pstmt.setDate( 6, (Date)d );

pstmt.setDate( 6, new java.sql.Date( d.getTime() ) );

或至

pstmt.setDate( 6, new java.sql.Date( cal.getTimeInMillis() ) );
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
System.out.println("Current Date : "+dateFormat.format(date));

使用插入查詢,您可以將此日期對象保存到數據庫。

    long timeInMillis = System.currentTimeMillis();
    Calendar cal1 = Calendar.getInstance();
    cal1.setTimeInMillis(timeInMillis);
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy     hh:mm:ss a");
    String date=dateFormat.format(cal1.getTime());
    return date;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM