简体   繁体   中英

Convert 24 hour format to MySQL DATETIME format

I'm trying to convert 24 hour format time to datetime format so I can store it in Mysql as Datetime. I tried google but all the results come as other way around. For example, how to convert 21:30 to datetime format?

You can use the java.util.Date, define the time you want and the use the constructor of java.sql.Date and in the parameter use the function .getTime(), like this:

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

The java.sql.Date, only uses the day, month and year, if you want with hours, minutes and seconds, you use a second variable wich is of type java.sql.Time:

java.util.Date utilDate = new java.util.Date();
java.sql.Time sqlDate = new java.sql.Time(utilDate.getTime());

A MySQL DATETIME column stores both date and time, not just a time, and you don't ever format as string for sending to the database. Use a PreparedStatement to prevent SQL Injection attacks.

Examples 1:

Date now = new Date();

String sql = "INSERT INTO MyTable ( MyDateTime ) VALUES ( ? )";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    stmt.setTimestamp(1, new Timestamp(now.getTime()));
    stmt.executeUpdate();
}

Examples 2:

String dateText = "11/8/2015 1:35 PM";
Date dateTime = new SimpleDateFormat("M/d/yyyy h:mm a").parse(dateText);

String sql = "UPDATE MyTable SET MyDateTime = ? WHERE MyId = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    stmt.setTimestamp(1, new Timestamp(dateTime.getTime()));
    stmt.setInt(2, 1234);
    stmt.executeUpdate();
}

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