如何在SimpleDateFormat中将Z设置为时区 [英] How to set Z as timezone in SimpleDateFormat

查看:113
本文介绍了如何在SimpleDateFormat中将Z设置为时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码示例:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
System.out.println(dateFormat.getTimeZone());
System.out.println(dateFormat.parse(time));
//  dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));

我不想使用带注释的部分.

I don't want to use the commented section.

应该根据我在输入字符串中给出的 IST 来设置区域:

Zone should be set based on IST that I am giving in the input string:

String time ="2018-04-06 16:13:00 IST";

当前计算机区域是: America/New_York .我应该如何根据z将区域更改为IST?

Current machine zone is: America/New_York. How should I get zone changes to IST based on z?

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
String time ="2018-04-06 18:40:00 IST";
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));

以上运行正常,但我不想显式设置区域.应该根据我在输入时间字符串中提供的IST进行选择.

Above is running correctly but I don't want to set zone explicitly. It should be choosen based on IST I am giving in input time string.

推荐答案

    DateTimeFormatter formatter 
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss z", Locale.ENGLISH);
    String time ="2018-04-06 16:13:00 IST";
    ZonedDateTime dateTime = ZonedDateTime.parse(time, formatter);
    System.out.println(dateTime.getZone());

在我的Java 8上已打印

On my Java 8 this printed

亚洲/耶路撒冷

因此,显然IST被解释为以色列标准时间.在具有其他设置的其他计算机上,您会得到例如爱尔兰夏令时"的欧洲/都柏林"或印度标准时"的亚洲/加尔各答".无论如何,时区都来自与格式模式字符串中的模式字母(小写) z 匹配的缩写,我想这就是您的意思(?)

So apparently IST was interpreted as Israel Standard Time. On other computers with other settings you will instead get for instance Europe/Dublin for Irish Summer Time or Asia/Kolkata for India Standard Time. In any case the time zone comes from the abbreviation matching the pattern letter (lowercase) z in the format pattern string, which I suppose was what you meant(?)

如果您想在过于歧义的情况下控制时区的选择,则可以以这种方式构建格式化程序(从

If you want to control the choice of time zone in the all too frequent case of ambiguity, you may build your formatter in this way (idea stolen from this answer):

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("uuuu-MM-dd HH:mm:ss ")
            .appendZoneText(TextStyle.SHORT,
                    Collections.singleton(ZoneId.of("Asia/Kolkata")))
            .toFormatter(Locale.ENGLISH);

现在的输出是

亚洲/加尔各答

我正在使用并建议使用 java.time ,它已经过时了并且非常麻烦的 SimpleDateFormat 类.

I am using and recommending java.time over the long outdated and notoriously troublesome SimpleDateFormat class.

链接: Oracle教程:日期时间解释如何使用 java.time .

这篇关于如何在SimpleDateFormat中将Z设置为时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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