Java 如何使用自定义时区显示日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1166494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I display a date with a custom timezone?
提问by Kyle Boon
Lets say I have a string that represents a date that looks like this:
假设我有一个表示日期的字符串,如下所示:
"Wed Jul 08 17:08:48 GMT 2009"
“格林威治标准时间 2009 年 7 月 8 日星期三 17:08:48”
So I parse that string into a date object like this:
所以我将该字符串解析为这样的日期对象:
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZ yyyy");
Date fromDate = (Date)formatter.parse(fromDateString);
That gives me the correct date object. Now I want to display this date as a CDT value.
这给了我正确的日期对象。现在我想将此日期显示为 CDT 值。
I've tried many things, and I just can't get it to work correctly. There must be a simple method using the DateFormat class to get this to work. Any advice? My last attempt was this:
我已经尝试了很多东西,但我无法让它正常工作。必须有一个使用 DateFormat 类的简单方法才能使其工作。有什么建议吗?我最后一次尝试是这样的:
formatter.setTimeZone(toTimeZone);
String result = formatter.format(fromDate);
采纳答案by Jon Skeet
Use "zzz" instead of "ZZZ": "Z" is the symbol for an RFC822 time zone.
使用“zzz”代替“ZZZ”:“Z”是 RFC822 时区的符号。
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Having said that, my standard advice on date/time stuff is to use Joda Time, which is an altogether better API.
话虽如此,我对日期/时间的标准建议是使用Joda Time,这是一个更好的 API。
EDIT: Short but complete program:
编辑:简短但完整的程序:
import java.text.*;
import java.util.*;
public class Test
{
public List<String> names;
public static void main(String [] args)
throws Exception // Just for simplicity!
{
String fromDateString = "Wed Jul 08 17:08:48 GMT 2009";
DateFormat formatter = new SimpleDateFormat
("EEE MMM dd HH:mm:ss zzz yyyy");
Date fromDate = (Date)formatter.parse(fromDateString);
TimeZone central = TimeZone.getTimeZone("America/Chicago");
formatter.setTimeZone(central);
System.out.println(formatter.format(fromDate));
}
}
Output: Wed Jul 08 12:08:48 CDT 2009
输出:2009 年 7 月 8 日星期三 12:08:48 CDT
回答by laz
Using:
使用:
formatter.setTimeZone(TimeZone.getTimeZone("US/Central"));
outputs:
输出:
Wed Jul 08 12:08:48 CDT 2009
for the date in your example on my machine. That is after substituting zzz for ZZZ in the format string.
对于您在我机器上的示例中的日期。那是在格式字符串中用 zzz 替换 ZZZ 之后。
回答by hipsandy
Sorry for digging out an old-thread. But I was wondering if there is a java-class that holds all the time-zone-ids as a constant class. So instead of having to hard-code the time-zone-id while setting time-zone like this:
很抱歉挖出一个旧线程。但我想知道是否有一个 java-class 将所有 time-zone-ids 保存为一个常量类。因此,不必在像这样设置时区时对时区 id 进行硬编码:
formatter.setTimeZone(TimeZone.getTimeZone("US/Central"));
we would instead be doing something more standard/uniform:
相反,我们会做一些更标准/统一的事情:
formatter.setTimeZone(TimeZone.getTimeZone(SomeConstantClass.US_CENTRAL));
where SomeConstantClass.java is a class that holds the constants referring to the different time-zone-ids that are supported by the TimeZone class.
其中 SomeConstantClass.java 是一个类,其中包含引用 TimeZone 类支持的不同时区 ID 的常量。
回答by Basil Bourque
The modern way is with the java.time classes.
现代方法是使用 java.time 类。
ZonedDateTime
ZonedDateTime
Specify a formatting pattern to match your input string. The codes are similar to SimpleDateFormat
but not exactly. Be sure to read the class doc for DateTimeFormatter
. Note that we specify a Locale
to determine what human language to use for name of day-of-week and name of month.
指定格式模式以匹配您的输入字符串。代码类似于SimpleDateFormat
但不完全相同。请务必阅读DateTimeFormatter
. 请注意,我们指定 aLocale
来确定使用哪种人类语言来表示星期几和月份名称。
String input = "Wed Jul 08 17:08:48 GMT 2009";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EEE MMM dd HH:mm:ss z uuuu" , Locale.ENGLISH );
ZonedDateTime zdt = ZonedDateTime.parse ( input , f );
zdt.toString(): 2009-07-08T17:08:48Z[GMT]
zdt.toString(): 2009-07-08T17:08:48Z[GMT]
We can adjust that into any other time zone.
我们可以将其调整到任何其他时区。
Specify a proper time zone namein the format of continent/region
. Never use the 3-4 letter abbreviation such as CDT
or EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
以 格式指定正确的时区名称continent/region
。切勿使用 3-4 个字母的缩写,例如CDT
orEST
或,IST
因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。
I will guess that by CDT
you meant a time zone like America/Chicago
.
我猜CDT
你的意思是像America/Chicago
.
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime zdtChicago = zdt.withZoneSameInstant( z );
zdtChicago.toString() 2009-07-08T12:08:48-05:00[America/Chicago]
zdtChicago.toString() 2009-07-08T12:08:48-05:00[美国/芝加哥]
Instant
Instant
Generally best to work in UTC. For that extract an Instant
. The Instant
class represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).
通常最好在 UTC 中工作。为此,提取一个Instant
. 该Instant
级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。
This Instant
class is a basic building-block class of java.time. You can think of ZonedDateTime
as an Instant
plus a ZoneId
.
这个Instant
类是基本构建块类java.time的。您可以将其ZonedDateTime
视为Instant
加号ZoneId
。
Instant instant = zdtChicago.toInstant();
instant.toString(): 2009-07-08T17:08:48Z
Instant.toString(): 2009-07-08T17:08:48Z
About java.time
关于 java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to java.time.
现在处于维护模式的Joda-Time项目建议迁移到 java.time。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8and SE 9and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use….
- Java SE 8和SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用......。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。