如何在Java中将日期时间字符串转换为UTC? [英] How to convert a datetime string into UTC in Java?

查看:100
本文介绍了如何在Java中将日期时间字符串转换为UTC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自MS SQL Server数据库的时间戳字符串.其值为 2021-04-11 10:25:33.000 ,sql数据类型为datetime,时区为PST,即太平洋时间.如何使用Java将时间戳转换为UTC?我的预期结果是 2021-04-11T17:25:33.000 ,即UTC.

I have a timestamp string which comes from a MS SQL server database. Its value is 2021-04-11 10:25:33.000, sql data type is datetime and time zone is PST i.e. pacific time. How do I convert this timestamp to UTC with Java? My expected result is 2021-04-11T17:25:33.000 which is UTC.

注意-我只想使用Java 8时间库,即在包 java.time 中.我不要日历,日期,SimpleDateFormat等.

NOTE - I want to use only use Java 8 time libraries i.e. in the package java.time. I don't want Calendar, Date, SimpleDateFormat etc.

PS-最初,我试图在堆栈溢出时找到解决方案,但几分钟后却找不到任何东西.所有对我的问题的搜索量最高的搜索结果均提供了php,c#和javascript的解决方案.

PS - Initially, I tried to find a solution on stack overflow, but could not find anything for a few minutes. All the top searches for my question gave solutions in php, c# and javascript.

推荐答案

我合并了两个堆栈溢出帖子以获取所需的答案.复习我的答案会很高兴.

I combined two stack overflow posts to get the answer I need. It would be nice to get a review of my answer.

1-我在这里 https://stackoverflow.com/a/34605826/6648326 找到了一个可以正常工作的解决方案,但这会在我的时间戳中删除结尾的零.

1 - I found one partially working solution here https://stackoverflow.com/a/34605826/6648326, but it drops the trailing zeros in my timestamp.

2-这是解决尾随零问题的答案 https://stackoverflow.com/a/48043948/6648326

2 - Here is the answer to fix the trailing zeros problem https://stackoverflow.com/a/48043948/6648326

工作解决方案:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Temp {
    public static void main(String [] args){
        //America/Los_Angeles
        ZoneId usaPacific = ZoneId.of("America/Los_Angeles");
        String str = "2021-04-11 10:25:33.000";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        LocalDateTime localDateTime = LocalDateTime.parse(str, formatter);
        ZonedDateTime dateAndTimeInLosAngeles = ZonedDateTime.of(localDateTime, usaPacific );

        //2021-04-11T10:25:33-07:00[America/Los_Angeles]
        System.out.println("Current date and time in a particular timezone : " + dateAndTimeInLosAngeles);

        ZonedDateTime utcDate = dateAndTimeInLosAngeles.withZoneSameInstant(ZoneOffset.UTC);

        DateTimeFormatter formatterOut = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
        //2021-04-11T17:25:33Z
        System.out.println("Current date and time in UTC : " + utcDate.format(formatterOut));
    }
}

这篇关于如何在Java中将日期时间字符串转换为UTC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆