Java 日期时间转换为给定时区

2023-09-25Java开发问题
2

本文介绍了Java 日期时间转换为给定时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个格式为 Tue, 30 Apr 2019 16:00:00 +0800 的 DateTime,即 RFC 2822 格式日期

I have a DateTime in the format of Tue, 30 Apr 2019 16:00:00 +0800 which is RFC 2822 formatted date

我需要将其转换为 DateTime 中的给定时区,即 +0800

I need to convert this to the given timezone in the DateTime which is +0800

所以如果我总结一下,

DateGiven = Tue, 30 Apr 2019 16:00:00 +0800
DateWanted = 01-05-2019 00:00:00

如何在 Java 中实现这一点?我已经尝试了下面的代码,但它比当前时间少 08 小时,即

How can i achieve this in Java? I have tried the below code but it gives 08 hours lesser than the current time which is

30-04-2019 08:00:00

我试过的代码

String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date startDate = format.parse(programmeDetails.get("startdate").toString());

//Local time zone   
 SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

//Time in GMT
Date dttt= dateFormatLocal.parse( dateFormatGmt.format(startDate) );

推荐答案

在@ole v.v 的解释的帮助下,我将两个日期时间值分开1次2. 时区

with the help of @ole v.v's explanation i have separated the datetime value for two 1. time 2. timezone

然后我使用此编码来提取与给定时区相关的日期时间

then i used this coding to extract the datetime which is related to the given timezone

//convert datetime to give timezone 
    private static String DateTimeConverter (String timeVal, String timeZone)
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    SimpleDateFormat offsetDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

        offsetDateFormat2.setTimeZone(TimeZone.getTimeZone(timeZone));
        String result =null;
        try {
            result = offsetDateFormat2.format(format.parse(timeVal));
        } catch (java.text.ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }

这篇关于Java 日期时间转换为给定时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13