简体   繁体   English

如何在Java中将字符串转换为DateTime

[英]How to Convert String To DateTime in java

I am trying to store date in sql server 2005 i am used "datetime" data type in sql server and in java program i am passing string as date 我试图在SQL Server 2005中存储日期,我在SQL Server和Java程序中使用了“ datetime”数据类型,我将字符串作为日期传递

ex. 例如

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);
     }

the above code is working...but i want to use String DateStr = "12/12/2013"; 上面的代码正在工作...但我想使用String DateStr =“ 12/12/2013”​​; insted of d.getTime() bcoz i passed date as string to java function by using jquery datepicker 插入d.getTime() bcoz我通过使用jquery datepicker将日期作为字符串传递给java函数

You need to use a SimpleDateFormat to parse your String to a date and then use that date. 您需要使用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;
}

Input: 12/12/2013 Output: 1386786600000 输入: 12/12/2013输出: 1386786600000

First convert string in datetime object than you can directly pass d1 to your code 首先在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