hasi
hasi

Reputation: 16

Insert date to datetime type column

I want to insert a date to a mysql database table. The datatype of the related column in mysql database table is datetime. I used the following code.

String date="2013.05.15";
Timestamp timestamp = new Timestamp(Long.parseLong(date));

when I am inserting timestamp value, it throws numberformat exception. Anybody please tell me how to insert the value to the database. Thank You .

Upvotes: 0

Views: 545

Answers (2)

KhAn SaAb
KhAn SaAb

Reputation: 5366

Either use NOW() function of mysql or use timestamp to insert into mysql.

and make sure datatype of mysql field datetime

Timestamp timestamp = new Timestamp(new Date().getTime());
Timestamp dateForDb= timestamp;

insert dateForDb into your database.

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39457

You're not parsing the date correctly. Actually you're trying to
parse it as long which is a number, not a date. You can use this code.

    String date="2013.05.15";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
    Date dt = sdf.parse(date);
    Timestamp timestamp = new Timestamp(dt.getTime());

Upvotes: 2

Related Questions