如何使用timeoffset更改日期字符串的时间格式 [英] How to Change time format of date string using timeoffset

查看:164
本文介绍了如何使用timeoffset更改日期字符串的时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将日期字符串从Java中的另一个时区转换为UTC格式。我们只有时区偏移,例如 -06:00。谁能帮助我如何使用时区偏移量将日期时间转换为UTC格式。



谢谢



这适用于Java 1.7版。我尝试使用以下代码段,但收到与输出相同的输入。

  String dateInString = 02/04/2019 18:17 :15; 
SimpleDateFormat格式化程序= new SimpleDateFormat( MM / dd / yyyy HH:mm:ss);
formatter.setTimeZone(TimeZone.getTimeZone( UTC));
Date date = formatter.parse(dateInString);
DateFormat dateFormat = new SimpleDateFormat( MM / dd / yyyy HH:mm:ss);
dateFormat.setTimeZone(TimeZone.getTimeZone( + 5:30));
字符串dateStr = dateFormat.format(date);
System.out.println(dateStr);

输出
02/04/2019 18:17: 15

解决方案

不幸的是, TimeZone.getTimeZone(String ID) 返回:


指定的 TimeZone 或GMT区域(如果指定) ID无法理解


+ 5:30 时区无法理解,因此您将获得格林尼治标准时间。



更改为 GMT + 5:30 将使您的代码正常工作,即它将打印:

  02/04/2019 23:47:15 






请参见 TimeZone 有效的 ID 语法:


自定义时区ID的语法为:

 自定义ID:
GMT签署时间:分钟
GMT签署时间分钟
GMT签署时间
签署时间:
+-
营业时间:
数字
数字位数
分钟:
数字数字
数字:
之一0 1 2 3 4 5 6 7 8 9




如您所见,它必须始终以 GMT 开头。


I am trying to convert date string to UTC format from another time zone in Java. we have only time zone offset like "-06:00". Can any one help me how to convert the date time to UTC format using time zone offset.

Thanks

This for java version 1.7 . I have tried with following snippet but receiving the same input as output.

String dateInString = "02/04/2019 18:17:15";                
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatter.parse(dateInString);          
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");             
dateFormat.setTimeZone(TimeZone.getTimeZone("+5:30"));
String dateStr = dateFormat.format(date);
System.out.println(dateStr);

Output 02/04/2019 18:17:15

解决方案

Unfortunately, TimeZone.getTimeZone(String ID) returns:

the specified TimeZone, or the GMT zone if the given ID cannot be understood.

The "+5:30" time zone cannot be understood, so you get GMT.

Change to "GMT+5:30" will make your code work, i.e. it'll print:

02/04/2019 23:47:15


See the javadoc of TimeZone for valid ID syntax:

The syntax of a custom time zone ID is:

CustomID:
        GMT Sign Hours : Minutes
        GMT Sign Hours Minutes
        GMT Sign Hours
Sign: one of
        + -
Hours:
        Digit
        Digit Digit
Minutes:
        Digit Digit
Digit: one of
        0 1 2 3 4 5 6 7 8 9

As you can see, it must always start with GMT.

这篇关于如何使用timeoffset更改日期字符串的时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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