如何在 Java 中使用 TimeZone 处理夏令时

编程入门 行业动态 更新时间:2024-10-11 07:29:21
本文介绍了如何在 Java 中使用 TimeZone 处理夏令时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我必须在我的 Java 应用程序中打印 EST 时间.我已使用以下方法将时区设置为 EST:

I have to print the EST time in my Java application. I had set the time zone to EST using:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));

但是当在这个时区遵循夏令时时,我的代码没有打印正确的时间(它打印的时间少了 1 小时).

But when the daylight savings is being followed in this timezone, my code does not print the correct time (it prints 1 hour less).

无论是否遵守夏令时,如何让代码始终读取正确的时间?

How to make the code work to read the correct time always, irrespective of whether the daylight savings are being observed or not?

PS:我尝试将时区设置为 EDT,但并没有解决问题.

PS: I tried setting the timezone to EDT, but it doesn't solve the problem.

推荐答案

这是开始的问题:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));

应完全避免使用 3 个字母的缩写,以支持 TZDB 区域 ID.EST 是东部标准时间 - 标准时间从不遵守 DST;这不是一个完整的时区名称.它是用于时区部分的名称.(不幸的是,我还没有找到一个关于半时区"概念的好词.)

The 3-letter abbreviations should be wholeheartedly avoided in favour of TZDB zone IDs. EST is Eastern Standard Time - and Standard time never observes DST; it's not really a full time zone name. It's the name used for part of a time zone. (Unfortunately I haven't come across a good term for this "half time zone" concept.)

您想要一个完整的时区名称.例如,America/New_York 位于东部时区:

You want a full time zone name. For example, America/New_York is in the Eastern time zone:

TimeZone zone = TimeZone.getTimeZone("America/New_York"); DateFormat format = DateFormat.getDateTimeInstance(); format.setTimeZone(zone); System.out.println(format.format(new Date()));

更多推荐

如何在 Java 中使用 TimeZone 处理夏令时

本文发布于:2023-11-23 20:17:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622759.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:夏令时   如何在   Java   TimeZone

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!