java 如何使用java将当前日期和时间保存到数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15212832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:52:18  来源:igfitidea点击:

How to save current date and time to database using java?

javasqljakarta-eedatetime

提问by Daniel Morgan

I am using the following code to get the current date and time, but the output is not what I am expecting and I cant save it into database.

我正在使用以下代码获取当前日期和时间,但输出不是我所期望的,我无法将其保存到数据库中。

Output >> current: Tue Mar 05 09:58:26 EST 2013

输出 >> 当前:美国东部标准时间 2013 年 3 月 5 日星期二 09:58:26

Expected output >> current: 2013-03-05 9:58:26

预期输出 >> 当前:2013-03-05 9:58:26

 .....{  
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        try {
            System.out.println("current: " +parseFormat.parse(dateFormat.format(date)));
            return parseFormat.parse(dateFormat.format(date));
        } catch (ParseException ex) {
            Logger.getLogger(ConstructionModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        return date;
     }
        ......

        ps.setDate(....) <<< failed

Database

数据库

 name   type
 mydate Date

回答by amphibient

You don't need to parse before formatting:

您不需要在格式化之前解析:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date date = new Date();

String frmtdDate = dateFormat.format(date);

System.out.println("frmtdDate: " + frmtdDate);

However, if you are trying to fit the date into some DB statement, you should not do it in the form of text, instead use one of the JDBC setters that utilize java.sql.Dateor java.sql.Timestamp

但是,如果您尝试将日期放入某些 DB 语句中,则不应以文本形式进行,而应使用使用java.sql.Datejava.sql.Timestamp

回答by Igor Rodriguez

You need to use sql timestamp for saving to the database. Convert your java.util.Date to java.sql.Timestamp:

您需要使用 sql 时间戳来保存到数据库。将您的 java.util.Date 转换为java.sql.Timestamp

ps.setTimestamp(new java.sql.Timestamp(myDate.getTime()));

回答by Javier

formattakes a Dateand returns a formatted String. parsetakes a formatted Stringand returns a Dateobject. When you do parseFormat.parse(dateFormat.format(date))you are converting Dateto Stringand to Dateagain. The value that is printed is the default representation provided by Date.toString()instead of the formatted string.

format接受 aDate并返回一个格式化的String. parse接受格式化String并返回一个Date对象。当您这样做时,parseFormat.parse(dateFormat.format(date))您正在转换DateStringDate再次转换。打印的值是由Date.toString()而不是格式化字符串提供的默认表示。

       System.out.println("current: " +dateFormat.format(date));