Posted in

在 Java 中转换 java.sql.Timestamp 和 ZonedDateTime_AI阅读总结 — 包阅AI

包阅导读总结

1. `Java`、`Timestamp`、`ZonedDateTime`、`转换`、`时间操作`

2. 本文介绍了在 Java 中`java.sql.Timestamp`和`java.time.ZonedDateTime`之间的转换,包括二者的差异、不同的转换方法及使用的库,如通过`toInstant`方法和`Joda-Time`库,最后总结了相关内容。

3.

– 概述

– `java.sql.Timestamp`是处理 SQL `TIMESTAMP`数据类型的遗留类,与时间区无关。

– `java.time.ZonedDateTime`是 Java 8 引入的现代日期时间 API 的一部分,包含时区信息。

– `java.sql.Timestamp`转`ZonedDateTime`

– 方法 1:使用`toInstant`方法,先将`Timestamp`转`Instant`,再用系统默认时区转`ZonedDateTime`。

– 方法 2:使用`Joda-Time`库,先转`org.joda.time.DateTime`,再转`ZonedDateTime`。

– `ZonedDateTime`转`java.sql.Timestamp`

– 方法 1:使用`toInstant`和`Timestamp.from`,先将`ZonedDateTime`转`Instant`,再转`Timestamp`。

– 方法 2:使用`Joda-Time`库,先转`Joda-Time`的`DateTime`,再转`Timestamp`。

– 结论

– 探讨了`java.sql.Timestamp`和`ZonedDateTime`之间转换的方法和库。

思维导图:

文章地址:https://www.javacodegeeks.com/converting-between-java-sql-timestamp-and-zoneddatetime-in-java.html

文章来源:javacodegeeks.com

作者:Omozegie Aziegbe

发布时间:2024/6/27 11:37

语言:英文

总字数:912字

预计阅读时间:4分钟

评分:81分

标签:日期时间,Java 日期 API,java.sql.Timestamp,时间转换,ZonedDateTime


以下为原文内容

本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com

In Java, conversion between java.sql.Timestamp and java.time.ZonedDateTime can be essential for applications that interact with legacy systems that require this specific type and need to handle date and time operations. This guide will show various approaches to performing these conversions with code examples.

1. Overview

java.sql.Timestamp is a legacy class used for handling SQL TIMESTAMP data types, while java.time.ZonedDateTime is part of the modern Java Date-Time API introduced in Java 8. Converting between these two classes involves understanding their differences and using appropriate methods to bridge the gap.

1.1 Key Differences

  • java.sql.Timestamp: Represents a specific point in time, down to nanoseconds. It inherits from java.util.Date and is time-zone agnostic.
  • java.time.ZonedDateTime: Represents a date-time with a time-zone in the ISO-8601 calendar system.

2. Converting java.sql.Timestamp to ZonedDateTime

2.1 Approach 1: Using toInstant Method

The Timestamp class has a toInstant method that can convert the Timestamp to an Instant. We can then convert this Instant to a ZonedDateTime.

TimeStampToZonedDateTime.java

public class TimeStampToZonedDateTime {    public static void main(String[] args) {        // Current time as Timestamp        Timestamp timestamp = new Timestamp(System.currentTimeMillis());        // Convert to Instant        Instant instant = timestamp.toInstant();        // Convert Instant to ZonedDateTime with system default time zone        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());        // Print results        System.out.println("Timestamp: " + timestamp);        System.out.println("ZonedDateTime: " + zonedDateTime);            }}

The code block creates a Timestamp object representing the current time. Next, it converts the Timestamp to an Instant, a point in time with nanosecond precision. It then converts the Instant to a ZonedDateTime, which includes time-zone information using the system’s default time zone. From the location where the program is run, I get the following output:

Fig 1: Output from the example demonstrating the conversion of java.sql.Timestamp to ZonedDateTime using the toInstant method.
Fig 1: Output from the example demonstrating the conversion of java.sql.Timestamp to ZonedDateTime using the toInstant method.

2.2 Using Joda-Time Library

Joda-Time is a popular date and time manipulation library for Java applications. Developed to address limitations and complexities in the original Java date-time APIs, Joda-Time offers a comprehensive approach to handling date, time, and time zone-related operations.

To use the Joda-Time library in your project, first, you need to add the Joda-Time dependency to your pom.xml file if you are using Maven. Here is how you can add it:

pom.xml

<dependency>    <groupId>joda-time</groupId>    <artifactId>joda-time</artifactId>    <version>2.12.7</version></dependency>

Ensure you update the version to the latest available version if it differs.

Next, convert java.sql.Timestamp to org.joda.time.DateTime, and then to java.time.ZonedDateTime, following these steps:

ConvertToZonedDateTimeUsingJodaTime.java

public class ConvertToZonedDateTimeUsingJodaTime {    public static void main(String[] args) {        // Current time as Timestamp        Timestamp timestamp = new Timestamp(System.currentTimeMillis());        // Convert to Joda-Time DateTime        DateTime jodaDateTime = new DateTime(timestamp.getTime());        // Convert Joda-Time DateTime to java.time.ZonedDateTime        ZonedDateTime zonedDateTime = jodaDateTime.toGregorianCalendar().toZonedDateTime();        // Print results        System.out.println("Timestamp: " + timestamp);        System.out.println("Joda-Time DateTime: " + jodaDateTime);        System.out.println("ZonedDateTime: " + zonedDateTime);    }}

This code snippet demonstrates the process of converting the current time from a java.sql.Timestamp to an org.joda.time.DateTime, and then to a java.time.ZonedDateTime. It begins by creating a Timestamp object representing the current time. This Timestamp is then converted into a DateTime object using the Joda-Time library. Subsequently, the DateTime is converted into a ZonedDateTime by first converting it to a GregorianCalendar and then to a ZonedDateTime.

Example Output:

Timestamp: 2024-06-26 13:18:28.336Joda-Time DateTime: 2024-06-26T13:18:28.336+01:00ZonedDateTime: 2024-06-26T13:18:28.336+01:00[Africa/Lagos]

Note: The actual time values and time zone might differ based on when and where the code is executed.

3. Converting ZonedDateTime to java.sql.Timestamp

Now, let’s explore how to convert a ZonedDateTime to a java.sql.Timestamp.

3.1 Using toInstant and Timestamp.from

To convert a ZonedDateTime to a Timestamp, we can use the toInstant method to get an Instant and then convert this Instant to a Timestamp.

ZonedDateTimeToTimeStamp.java

public class ZonedDateTimeToTimeStamp {    public static void main(String[] args) {        // Current time as ZonedDateTime        ZonedDateTime zonedDateTime = ZonedDateTime.now();        // Convert to Instant        Instant instant = zonedDateTime.toInstant();        // Convert Instant to Timestamp        Timestamp timestamp = Timestamp.from(instant);        // Print results        System.out.println("ZonedDateTime: " + zonedDateTime);        System.out.println("Timestamp: " + timestamp);    }}

This code snippet begins by obtaining an Instant representation of the ZonedDateTime using the toInstant method. This Instant captures the exact moment in time without any time zone information. Then, utilizing the Timestamp.from method, the Instant is converted back into a java.sql.Timestamp which is suitable for interacting with legacy systems that require this specific type.

3.2 Using Joda-Time Library

Let’s now explore how we can convert ZonedDateTime to java.sql.Timestamp using the Joda-Time class.

JodaDateTimeToTimestamp.java

public class JodaDateTimeToTimestamp {    public static void main(String[] args) {                // Current time as ZonedDateTime        ZonedDateTime zonedDateTime = ZonedDateTime.now();                // Current time as Joda-Time DateTime        DateTime jodaDateTime = new DateTime(zonedDateTime.toInstant().toEpochMilli());        // Convert Joda-Time DateTime to java.sql.Timestamp        Timestamp timestamp = new Timestamp(jodaDateTime.getMillis());        // Print results        System.out.println("Joda-Time DateTime: " + jodaDateTime);        System.out.println("Timestamp: " + timestamp);    }}

The above code snippet retrieves the current time as a ZonedDateTime using the system’s default time-zone. It then converts this ZonedDateTime to an Instant and subsequently to milliseconds since the Unix epoch. Using these milliseconds, it initializes a DateTime object from the Joda-Time library. Next, it converts this DateTime object to a java.sql.Timestamp.

Output is:

Joda-Time DateTime: 2024-06-26T14:07:12.196+01:00Timestamp: 2024-06-26 14:07:12.196

4. Conclusion

In this article, we explored some methods and libraries for converting between java.sql.Timestamp and ZonedDateTime in Java. We began by using the java.time package’s toInstant method to convert from Timestamp to ZonedDateTime. Additionally, we delved into utilizing the Joda-Time library for these conversions.

5. Download the Source Code

This article covers the conversion between Java SQL Timestamp and ZonedDateTime.