java 在java中将字符串转换为'timestamp with timezone'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38563099/
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-11-03 03:32:09  来源:igfitidea点击:

Converting string to 'timestamp with timezone' in java

javadatedatetime

提问by Random Coder

I have a string "2016-07-21T21:30:47.492+0000" I want to save it in DB in a column that has the datatype 'TIMESTAMP WITH TIMEZONE'. Kindly suggest the solution.

我有一个字符串“2016-07-21T21:30:47.492+0000”,我想将它保存在数据库中数据类型为“TIMESTAMP WITH TIMEZONE”的列中。请提出解决方案。

This is what I did:

这就是我所做的:

final SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSX");
final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
final Date d1 = mdyFormat.parse(strDate);
final String mdx = sdf.format(d1);

回答by Basil Bourque

You are using troublesome old classes now supplanted by java.time classes.

您正在使用麻烦的旧类,现在已被 java.time 类取代。

Here is how to follow the advice given by Jon Skeet posted in a comment on the Question.

以下是如何遵循 Jon Skeet 在对该问题的评论中发表的建议。

java.time

时间

The java.timeframework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Timeteam also advises migration to java.time.

java.time框架是建立在Java 8和更高版本。这些类取代了旧的麻烦的日期时间类,例如java.util.Date, .Calendar, & java.text.SimpleDateFormat。该乔达时球队还建议迁移java.time。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backportand further adapted to Android in ThreeTenABP.

多的java.time功能后移植到Java 6和7在ThreeTen-反向移植和在进一步适于到Android ThreeTenABP

OffsetDateTime

OffsetDateTime

You can parse that input string as an OffsetDateTimeobject.

您可以将该输入字符串解析为OffsetDateTime对象。

OffsetDateTime odt = OffsetDateTime.parse( "2016-07-21T21:30:47.492+0000" );

If your JDBC driver complies with JDBC 4.2 or later, you may be able to pass/fetch to SQL via the PreparedStatement::setObjectand ResultSet::getObjectmethods. If not, convert to the old java.sql type.

如果您的 JDBC 驱动程序符合 JDBC 4.2 或更高版本,则您可以通过PreparedStatement::setObjectResultSet::getObject方法向 SQL 传递/获取。如果不是,则转换为旧的 java.sql 类型。

Converting requires an Instantobject. An Instantis a more basic building-block class in java.time, lacking the flexibility of an OffsetDateTime. The Instantclass represents a moment on the timeline in UTCwith a resolution up to nanoseconds. Extract an Instantfrom that OffsetDateTime.

转换需要一个Instant对象。AnInstant是 java.time 中更基本的构建块类,缺乏OffsetDateTime. 该Instant级表示时间轴上的时刻UTC,分辨率高达纳秒。Instant从中提取一个OffsetDateTime

Instant instant = odt.toInstant();

Pass the Instantto a new method added to the old java.sql class.

将 传递Instant给添加到旧 java.sql 类的新方法。

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

Then call the PreparedStatement::setTimestampand ResultSet::getTimestampmethods.

然后调用PreparedStatement::setTimestampResultSet::getTimestamp方法。

myPreparedStatement.setTimestamp( 1 , ts );
…
java.sql.Timestamp ts = myResultSet.getTimestamp( 1 );

After fetching a java.sql.Timestamp, immediately convert to a java.time class, Instant. Use the java.sql classes only where direct support for java.time types is lacking in your JDBC driver, and even then, minimize your use of the java.sql classes. Do your business logic work in java.time.

获取 a 后java.sql.Timestamp,立即转换为 java.time 类,Instant. 仅在 JDBC 驱动程序中缺少对 java.time 类型的直接支持时才使用 java.sql 类,即使这样,也要尽量减少对 java.sql 类的使用。在 java.time 中执行您的业务逻辑。

Instant instant = ts.toInstant(); 

Confusing class names

混淆类名

Do not confuse the two old Dateclasses bundled with Java. The java.util.Daterepresents a date anda time-of-day. A java.sql.Dateis intended to represent only a date-only value without a time-of-day (but confusing actually does have a time-of-day due to it being a clumsy hack of an awkward class design).

不要混淆Date与 Java 捆绑的两个旧类。该java.util.Date代表的日期时间的一天。Ajava.sql.Date旨在仅表示没有时间的仅日期值(但混淆实际上确实有时间,因为它是笨拙的类设计的笨拙黑客)。

Avoid the java.util.Dateand java.util.Calendarand java.text.SimpleDateFormatclasses entirely. And minimize your use of the java.sql.Date/.Time/.Timestampclasses as discussed above.

完全避免java.util.Datejava.util.Calendarjava.text.SimpleDateFormat类。并最大限度地减少您的使用java.sql.Date/ .Time/.Timestamp以上讨论班。

回答by AJ.

Your code is having one problem

您的代码有一个问题

 String strDate = "2016-07-21T21:30:47.492+0000"; 
        final SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSX");
     // include `T` as well

    final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    final Date d1;
            try {
                d1 = mdyFormat.parse(strDate);
// to add time zone you  can use below line 
//  sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
                String mdx = sdf.format(d1);
                System.out.println(mdx);
            } catch (ParseException ex) {

            }

Output without sdf.setTimeZone(TimeZone.getTimeZone("UTC"))

输出无 sdf.setTimeZone(TimeZone.getTimeZone("UTC"))

22-07-2016

22-07-2016

Output with sdf.setTimeZone(TimeZone.getTimeZone("UTC"))

输出与 sdf.setTimeZone(TimeZone.getTimeZone("UTC"))

21-07-2016

21-07-2016

TimeZone.getDefault()gets the system's default timezone.

TimeZone.getDefault()获取系统的默认时区。