Nilesh12
Nilesh12

Reputation: 99

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

Upvotes: 1

Views: 11462

Answers (3)

user3040553
user3040553

Reputation: 1

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

Upvotes: 0

Vicky Thakor
Vicky Thakor

Reputation: 3916

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

Upvotes: 0

Rahul
Rahul

Reputation: 45070

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());
...

Upvotes: 7

Related Questions