简体   繁体   中英

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 .

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

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.

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