簡體   English   中英

如何在Java中將字符串轉換為DateTime

[英]How to Convert String To DateTime in java

我試圖在SQL Server 2005中存儲日期,我在SQL Server和Java程序中使用了“ datetime”數據類型,我將字符串作為日期傳遞

例如

String DateStr = "12/12/2013";

Date d = new Date();
java.sql.Date d1 = new java.sql.Date(d.getTime());

String sql = "INSERT INTO info (date) VALUES ( ? )";

try {
      pstmt = con.prepareStatement(sql);
      pstmt.setDate(1, d1);
      pstmt.executeUpdate();
     } catch (SQLException e) {
            System.out.println("Error:" + e);
     }

上面的代碼正在工作...但我想使用String DateStr =“ 12/12/2013”​​; 插入d.getTime() bcoz我通過使用jquery datepicker將日期作為字符串傳遞給java函數

您需要使用SimpleDateFormat將String解析為一個日期,然后使用該日期。

Date d = new SimpleDateFormat("dd/MM/yyyy").parse(DateStr); // This throws a ParseException

// Rest everything stays pretty much the same
java.sql.Date d1 = new java.sql.Date(d.getTime());
...
public long convertLong(String value) {
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    Date getDate = null;
    long returnDate = 0l;
    try {
        getDate = (Date) formatter.parse(value);
        returnDate = getDate.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return returnDate;
}

輸入: 12/12/2013輸出: 1386786600000

首先在datetime對象中轉換字符串,然后才能將d1直接傳遞給代碼

String DateStr = "12/12/2013";
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy ");
DateTime dt = formatter.parseDateTime(DateStr);
String sql = "INSERT INTO info (date) VALUES ( dt )";
try {
      pstmt = con.prepareStatement(sql);
      pstmt.setDate(1, d1);
      pstmt.executeUpdate();
     } 
catch (SQLException e) {
            System.out.println("Error:" + e);
     }

暫無
暫無

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

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