简体   繁体   English

Java代码,用于将东部日期和时间作为日期格式插入数据库

[英]Java code for getting Eastern date and time as date format to insert into database

I am using the java code like below to get the current eastern date and time and it should be inserted to database in date format. 我正在使用如下所示的Java代码来获取当前的东部日期和时间,并且应该以日期格式将其插入数据库。 Using the below code I am able to get the eastern date and time in string format as expected, but I can't insert this string format in SQL database because the column being used in database to store is of type datetime. 使用下面的代码,我可以按预期的字符串格式获取东部日期和时间,但是由于在数据库中用于存储的列的类型为datetime,所以无法在SQL数据库中插入此字符串格式。 I also tried changing the formatted Eastern time zone date and time to date type but it returns the date and time in GMT format again. 我还尝试将格式化的东部时区日期和时间更改为日期类型,但它再次以GMT格式返回日期和时间。

java.util.Date date = new java.util.Date();
java.util.Date time = new Timestamp(date.getTime());
SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss.ms");
TimeZone timeZone = TimeZone.getTimeZone("America/New_York"); 
formatter.setTimeZone(timeZone);

System.out.println("EST: " + formatter.format(time)); // Prints date as 2016-03-18 03:12:16.1216 which is string format

java.util.Date time1 = formatter.parse(formatter.format(time));

System.out.println("EST Time Zone: " + time1); // Prints date as Fri Mar 18 07:04:36 GMT 2016 which is date format

//Code to insert into database
dataSource = DataSourceFactoryUtil.initDataSource("net.sourceforge.jtds.jdbc.Driver",
PortletProps.get("exampledatabase.db.url"), PortletProps.get("exampledatabase.db.user"),
PortletProps.get("exampledatabase.db.password"), StringPool.BLANK);

connection = dataSource.getConnection();
stmt = connection.createStatement();
String insertQuery = "INSERT INTO [exampletable] ([Firstname], [Lastname], [address], [Time]) VALUES ('"
                        + firstname + "', '" + lastname + "', '" + address + "', '" + time1 + "')";
stmt.executeUpdate(insertQuery);

In above code, the first System.out.println is printing the date in EST which is as expected to be inserted in database, but I can't insert it as it is in string type, and I get the error as: 在上面的代码中,第一个System.out.println将在EST中打印日期,该日期预计将插入数据库中,但是我无法按字符串类型插入日期,并且出现以下错误:

Conversion failed when converting date and/or time from character string. 从字符串转换日期和/或时间时转换失败。

Another System.out.println gives the output in date format but it is not in EST. 另一个System.out.println以日期格式给出输出,但不在EST中。

How is it possible to get the output as format 2016-03-18 03:12:16.1216, and in date type instead of string so that I can insert into the database which has datetime type as a column. 如何获得格式为2016-03-18 03:12:16.1216的输出,以及日期类型而不是字符串的输出,以便我可以将日期时间类型作为列插入数据库。

The Answer by Alisson Vieira is correct but uses outmoded classes. Alisson Vieira答案是正确的,但使用了过时的类。

Do not use strings for date-time values, use date-time types. 不要将字符串用于日期时间值,而应使用日期时间类型。

Do not use the old date-time classes bundled with the earliest versions of Java, such as java.util.Date/.Calendar. 不要使用与最早的Java版本捆绑在一起的旧的日期时间类,例如java.util.Date/.Calendar。 They have proven to be poorly designed, confusing, and troublesome. 它们被证明设计不当,令人困惑且麻烦。 Those classes have been supplanted by the java.time framework built into Java 8 and later. 这些类已被Java 8及更高版本中内置的java.time框架取代。

A java.time.Instant is a moment on the timeline in UTC. java.time.Instant是UTC时间轴上的时刻。 You should do most of your work, your business logic, your database storage, in UTC. 您应该在UTC中完成大部分工作,业务逻辑和数据库存储。 Use a time zone only when required by the user or data sink. 仅在用户或数据接收器要求时才使用时区。

Instant instant = Instant.now();

Eventually the JDBC drivers will be updated to deal directly with the java.time types. 最终,JDBC驱动程序将被更新以直接处理java.time类型。 Until then we must continue to depend on the java.sql types for transferring data in/out of the database. 在此之前,我们必须继续依赖java.sql类型将数据传入/传出数据库。 But minimize your use of these classes; 但是,请尽量减少使用这些类。 convert to java.time as soon as possible in your work flow. 在您的工作流程中尽快转换为java.time。

In your database use the standard TIMESTAMP WITH TIME ZONE type to define the date-time column, or the equivalent if your database is not compliant. 在数据库中,使用标准的TIMESTAMP WITH TIME ZONE类型定义日期时间列,如果数据库不兼容,则使用等效类型。 You should almost never use the without time zone type. 您几乎永远不要使用without time zone类型。

The java.sql.Timestamp class maps to the java.time.Instant type. java.sql.Timestamp类映射到java.time.Instant类型。 To this old class a few new methods have been added for conversion to/from java.time such as toInstant and from( Instant ) . 在这个旧类中,添加了一些新的方法来转换到java.time或从java.time转换,例如toInstantfrom( Instant )

java.sql.Timestamp ts = java.sql.Timestamp.from( instant );

You should always use PreparedStatement to interact with your database for multiple reasons. 出于多种原因,您应该始终使用PreparedStatement与数据库进行交互。 One very important reason is to eliminate the risk of SQL Injection attacks. 一个非常重要的原因是消除SQL注入攻击的风险。

myPreparedStatement.setTimestamp( 4 , ts );

To retrieve use a java.sql.Timestamp to get the data, then convert to java.time. 要进行检索,请使用java.sql.Timestamp获取数据,然后将其转换为java.time。

java.sql.Timestamp ts = myResultSet.getTimestamp( 4 );
Instant instant = ts.toInstant();

Notice that nowhere in the code above did we deal with any particular timezone. 请注意,上面的代码中没有任何地方处理任何特定的时区。 We use UTC all the way through, Java ↔ JDBC ↔ SQL ↔ Database. 我们一直使用UTC ,包括Java↔JDBC↔SQL↔数据库。 And nowhere did we use Strings for our date-time values. 而且我们在任何地方都没有使用Strings作为日期时间值。

To see the wall-clock time for a particular time zone, apply a time zone ( ZoneId ) to get a ZonedDateTime . 要查看特定时区的挂钟时间 ,请应用时区( ZoneId )以获取ZonedDateTime Use proper time zone names, never the 3-4 letter codes such as EST as these are neither standardized nor unique. 使用正确的时区名称,切勿使用3-4字母代码(例如EST因为它们既不是标准化的也不是唯一的。

ZoneId zoneId = ZoneId.of( "America/New_York" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

To see a textual representation of that date-time value in standard ISO 8601 format, merely call toString . 要查看标准ISO 8601格式的日期时间值的文本表示形式,只需调用toString Example output: 2016-03-17T05:19:24.679Z . 输出示例: 2016-03-17T05:19:24.679Z

String output = zdt.toString();

To generate strings in other formats, search Stack Overflow for many examples on using DateTimeFormatter . 要生成其他格式的字符串,请在Stack Overflow中搜索有关使用DateTimeFormatter许多示例。

java.sql.Date sqlDate = new java.sql.Date(time1.getTime());

Try to use the java.sql.Date type into your insert SQL. 尝试在插入SQL中使用java.sql.Date类型。

How you're attempting to insert the record? 您如何尝试插入记录? Are you using some library? 您在使用图书馆吗?

@Edit @编辑

The System.out.print() doesn't handles the date as the JDBC does. System.out.print()不像JDBC那样处理日期。 The first calls the toString() method of Date instance, and the JDBC uses the getTime() , aka the milliseconds representation of the Date. 第一个调用Date实例的toString()方法,而JDBC使用getTime() ,也就是Date的毫秒表示形式。

@Edit2 @ Edit2

Change stmt = connection.createStatement(); 更改stmt = connection.createStatement();

to

PreparedStatement stmt=connection.prepareStatement("INSERT INTO exampleTable (Firstname, Lastname, address, Time) VALUES (?, ?, ?, ?)");
stmt.setString(1, firstname);
stmt.setString(2, lastname);
stmt.setString(3, address);
stmt.setTimestamp(4, new java.sql.Date(time1.getTime()));
stmt.executeUpdate();      

I am able to get date and time in EST datetime format with these 2 lines of codes: 我可以通过以下两行代码以EST datetime格式获取日期和时间:

TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
Timestamp timestamp = new Timestamp(new Date().getTime());

I get the output as EST date and time: 2016-03-23 03:12:16.1216 我得到的输出为EST日期和时间:2016-03-23 03:12:16.1216

Here is the working code including the code that I had provided while asking the question: 这是工作代码,包括我在提问时提供的代码:

TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
Timestamp timestamp = new Timestamp(new Date().getTime());

//Code to insert into database
dataSource = DataSourceFactoryUtil.initDataSource("net.sourceforge.jtds.jdbc.Driver",
PortletProps.get("exampledatabase.db.url"), PortletProps.get("exampledatabase.db.user"),
PortletProps.get("exampledatabase.db.password"), StringPool.BLANK);

connection = dataSource.getConnection();
stmt = connection.createStatement();
String insertQuery = "INSERT INTO [exampletable] ([Firstname], [Lastname], [address], [Time]) VALUES ('"
                        + firstname + "', '" + lastname + "', '" + address + "', '" + timestamp + "')";
stmt.executeUpdate(insertQuery);

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

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