将java.sql.Timestamp转换为java.util.Calendar ISO 8601格式 [英] Convert java.sql.Timestamp to java.util.Calendar ISO 8601 format
问题描述
我必须将更新时间存储在 dynamodb
中,同时浏览 dynamodb
的文档,发现我们可以构建如果我们以ISO 8601的格式存储索引,则为索引。但是在应用程序中,我有 java.sql.timestamp
。如何转换它?
I have to store updated time in dynamodb
, while going through the document of dynamodb
found out we can build an index if we store it in the format of ISO 8601. But in application I have java.sql.timestamp
. How can I convert it?
推荐答案
java.time
第一个答案,不要使用 java.sql.Timestamp
。这堂课早已过时了。取一个 Instant
。 Instant
是 java.time
(现代Java日期和时间API,也称为JSR 310)中的类之一。与旧类相比,该API更好用。假设 inst
是您的 Instant
:
First answer, don’t use java.sql.Timestamp
. This class is long outmoded. Get an Instant
instead. Instant
is one of the classes in java.time
, the modern Java date and time API also known as JSR 310. This API is so much nicer to work with than the old classes. Assuming inst
is your Instant
:
String iso8601String = inst.toString();
System.out.println(iso8601String);
在我的计算机上,这只是打印的
On my computer this just printed
2017-12-13T11:04:59.282Z
The <现代类的code> toString 方法产生ISO 8601格式,这使您的任务非常容易。
The toString
methods of the modern classes produce ISO 8601 format, which makes your task very easy.
转换您的时间戳
由于(据我所知),您无法从旧版代码中获取 Timestamp
对象可以立即进行升级:首先要做的是将其转换为 Instant
。然后,您可以按照上述步骤进行操作。
Since (as I understand) you get your Timestamp
object from legacy code that you cannot afford to upgrade just now: The first thing to do is to convert it to an Instant
. Then you may proceed as above.
我认为 ts
是您的时间戳。如果您使用的是Java 8或更高版本:
I assume that ts
is your timestamp. If you are using Java 8 or later:
String iso8601String = ts.toInstant().toString();
如果您使用的是Java 6或7,则需要获得ThreeTen Backport(下面的链接) 。这是JSR 310向上述Java版本的反向移植。由于在这些版本中,转换方法不是内置在 Timestamp
类中的,所以转换的方式略有不同,其他所有内容都是相同的。我尚未测试以下代码行,因此请耐心输入错误。
If you are using Java 6 or 7, you will need to get the ThreeTen Backport (link below). This is the backport of JSR 310 to the mentioned Java versions. Since in these versions, the conversion method isn’t built into the Timestamp
class, the conversion happens a little differently, everything else is the same. I have not tested the following code line, so please bear with any typo.
String iso8601String = DateTimeUtils.toInstant(ts).toString();
链接
- ThreeTen Backport homepage
- Java Specification Request (JSR) 310
- Oracle tutorial trail: Date Time
这篇关于将java.sql.Timestamp转换为java.util.Calendar ISO 8601格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!