简体   繁体   中英

Coverting a string into timestamp java mysql

My csv file has the following format 26/02/2014 17:20:17 . I've stored it in a string array in my program as value[0].

How would I go about converting it into a timestamp that can be stored into a DATETIME column in mysql eg 2014-02-26 17:20:17

Sounds like you are working with date formats.

In java you can get a date object by using SimpleDateFormat.

public java.sql.Date convert(String value) throws Exception {
   return new java.sql.Date(new SimpleDateFormat("dd/MM/yyyy  HH:mm:ss").parse(value).getTime());
}

Note: Throwing a general exception is a bad practice SimpleDateFormat is expensive to create so try to cache the formatter to be used repetitively. Also SimpleDateFormat is not thread safe

You can set the sql date into your prepared statement.

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