简体   繁体   中英

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

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"; insted of d.getTime() bcoz i passed date as string to java function by using jquery datepicker

You need to use a SimpleDateFormat to parse your String to a date and then use that date.

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

First convert string in datetime object than you can directly pass d1 to your code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM