简体   繁体   English

MySQL | MySQL和Java中的日期时间

[英]MySQL | Datetime in MySQL and Java

I have a little question. 我有一个小问题。 How does "DATETIME" in MySQL work? MySQL中的“ DATETIME”如何工作? How can I put in the current system time in with Java and get it again? 如何使用Java输入当前系统时间并重新获取? And how can I get the time between the DATETIME in the database and the current time of the Java server in seconds? 以及如何获取数据库中DATETIME到Java服务器当前时间之间的时间(以秒为单位)?

Thanks! 谢谢!

You can use Timestamp to insert date and time into DateTime type of attributes. 您可以使用时间戳将日期和时间插入属性的DateTime类型。 Check the code below I think its self explaining. 检查下面的代码,我认为它可以自我解释。

public class JavaApplication {

private static final String DATABASE_URL = "jdbc:mysql://localhost/test?characterEncoding=utf8";
private static final String DATABASE_USER = "root";
private static final String DATABASE_PASSWORD = "";
private static Connection con;
public static void main(String[] args) {
    try {
        Timestamp date = new Timestamp(System.currentTimeMillis());
        MysqlDataSource ds = new MysqlDataSource();
        ds.setUrl(DATABASE_URL);
        ds.setUser(DATABASE_USER);
        ds.setPassword(DATABASE_PASSWORD);
        con = ds.getConnection();
        PreparedStatement ps = con.prepareStatement("INSERT INTO tablename (date) VALUES (?)");
        ps.setTimestamp(1, date);
        ps.executeUpdate();
        ps = con.prepareStatement("SELECT * FROM tablename");
        ResultSet rs = ps.executeQuery();
        while(rs.next()){
            System.out.println("Date in database: "+rs.getTimestamp("date"));
            System.out.println("Time difference between server and database record in seconds: "+(rs.getTimestamp("date").getTime()-System.currentTimeMillis())/1000);
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM