java - 如何从 SQL 日期时间 UTC 转换为 LocalDateTime 并再次转换回来

标签 java mysql

代码应该从数据库中获取日期和时间,将其标记为 UTC(或者也许它应该已经知道它是 UTC?),将其转换为本地时区,然后将日期和时间作为时间戳返回.

目前代码仅打印出数据库中的日期/时间并将本地时间保存到数据库中。

我对代码的解释是否错误?我是否缺少转换时间的步骤?

感谢您的任何额外帮助


package Utils;

import java.sql.Date;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;


public class DateTimeConverter {

    public static Timestamp toLocalDateTime(Timestamp utc){
        //identify as UTC
        ZonedDateTime utcZonedDateTime = ZonedDateTime.ofInstant(utc.toInstant(), ZoneId.of("UTC"));
        Instant timestamp = utcZonedDateTime.toInstant();
        //set the timestamp to the systems default zone
        ZonedDateTime utcToLocal = timestamp.atZone(ZoneId.systemDefault());

        System.out.println(Timestamp.from(utcToLocal.toInstant()));

        return Timestamp.from(utcToLocal.toInstant());
    }

    public static Timestamp toUTC(Timestamp ldt){
        //identify as systems default zoneid
        ZonedDateTime localZDT = ZonedDateTime.ofInstant(ldt.toInstant(), ZoneId.systemDefault());
        Instant timestamp = localZDT.toInstant();
        //set the timestamp to UTC zoneid
        ZonedDateTime localToUTC = timestamp.atZone(ZoneId.of("UTC"));

        System.out.println(Timestamp.from(localToUTC.toInstant()));

        return Timestamp.from(localToUTC.toInstant());

    }

}

最佳答案


    public static Timestamp toLocalDateTime(Timestamp utc){

        LocalDateTime ldt = utc.toLocalDateTime();
        ZonedDateTime zdt = ldt.atZone(ZoneId.of("UTC"));
        ZonedDateTime newZdt = zdt.withZoneSameInstant(ZoneId.systemDefault());
        LocalDateTime newLdt = newZdt.toLocalDateTime();

        return Timestamp.valueOf(newLdt);

    }

    public static Timestamp toUTC(Timestamp ts){

        LocalDateTime ldt = ts.toLocalDateTime();
        ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
        ZonedDateTime newZdt = zdt.withZoneSameInstant(ZoneId.of("UTC"));
        LocalDateTime newLdt = newZdt.toLocalDateTime();

        return Timestamp.valueOf(newLdt);

    }

关于java - 如何从 SQL 日期时间 UTC 转换为 LocalDateTime 并再次转换回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60418118/

相关文章:

mysql - 根据子查询中的计数显示表结果

mysql - 在 MAMP/DB 中找不到 MAMP PRO MySQL 数据库文件夹

java - 如何写一个容易维护的概率算法?

java - 如何通过 JVMTI 接口(interface)使用 jmethod id 获取声明该方法的类

java - tomcat spring项目上运行HotswapAgent的异常

javascript - 当重新加载包含 mysql 数据的表的页面时,它应该转到表的特定部分

php - 选择最近 7 天内上传的数据

java - 如何在java套接字编程中使用单个服务器创建多个客户端?

java - 禁用奥利奥通知点

php - 尝试检索结果时,使用 PHP 类连接到数据库不起作用