基于 Java/Groovy 的 TimeZone 日期时间转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20084820/
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
Date Time Conversion based on the TimeZone Java/Groovy
提问by monal86
I am in MST and I want my Date in PST. I set the timeZone that I want.
Now if i do c.getTime()
I always get my server time.
Instead I want Pacific Date time. Please help
How to get the date time Object in the specified timezone.
我在 MST,我希望我的日期在 PST。我设置了我想要的时区。现在,如果我这样做,c.getTime()
我总能得到我的服务器时间。相反,我想要太平洋日期时间。请帮助如何获取指定时区中的日期时间对象。
Calendar c= Calendar.getInstance();
TimeZone timezone= TimeZone.getTimeZone("PST");
c.setTimeZone(timezone)
回答by Adrian Pang
The Java Date object do not have a timezone -- it just represents a point in time.
Java Date 对象没有时区——它只是代表一个时间点。
If you would like to format a date into a timezone, you can set it in the DateFormat class. For example:
如果要将日期格式化为时区,可以在 DateFormat 类中进行设置。例如:
Date date = new Date ();
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println(df.format(date));
df.setTimeZone(TimeZone.getTimeZone("EST"));
System.out.println(df.format(date));
will display a time in PST, then a time in EST.
将显示 PST 时间,然后显示 EST 时间。
回答by tim_yates
回答by dmahapatro
?TimeZone.setDefault(TimeZone.getTimeZone('PST'))
println new Date() //PST time
You can set the default timezone to PST/MST according to your need and then get the date. I would do this in a test method, if possible.
您可以根据需要将默认时区设置为 PST/MST,然后获取日期。如果可能,我会在测试方法中执行此操作。
回答by Basil Bourque
UPDATE:The Joda-Timeproject has been succeeded by the java.timeclasses. See this other Answer.
UPDATE:该乔达时间的项目已被成功java.time类。请参阅此其他答案。
(a) Use Joda-Time(or new JSR 310 built into Java 8). Don't even think about using the notoriously bad java.util.Date/Calendar.
(a) 使用Joda-Time(或 Java 8 中内置的新 JSR 310)。甚至不要考虑使用臭名昭著的 java.util.Date/Calendar。
(b) Your question is not clear. Your comments on answers talk about comparing, but you say nothing about comparing in your question.
(b) 你的问题不清楚。您对答案的评论谈到了比较,但您在问题中没有提及比较。
(c) Avoid the use of 3-letter time zone abbreviations. Read note of deprecation in Joda-Time doc for TimeZoneclass.
(c) 避免使用 3 个字母的时区缩写。阅读 Joda-Time 文档中TimeZone类的弃用说明。
(d) Avoid default time zone. Say what you mean. The time zone of your computer can change intentionally or not.
(d) 避免默认时区。说出你的意思。您计算机的时区可以有意或无意地更改。
(e) Search StackOverflow for 'joda' for lots of code snippets and examples.
(e) 在 StackOverflow 中搜索“joda”以获取大量代码片段和示例。
(f) Here's some Joda-Time example code to get you started.
(f) 这里有一些 Joda-Time 示例代码可以帮助您入门。
// ? 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Specify your time zone rather than rely on default.
org.joda.time.DateTimeZone californiaTimeZone = org.joda.time.DateTimeZone.forID( "America/Los_Angeles" );
org.joda.time.DateTimeZone denverTimeZone = org.joda.time.DateTimeZone.forID( "America/Denver" );
org.joda.time.DateTime nowDenver = new org.joda.time.DateTime( denverTimeZone );
org.joda.time.DateTime nowCalifornia = nowDenver.toDateTime( californiaTimeZone );
// Same moment in the Universe's timeline, but presented in the local context.
System.out.println( "nowDenver: " + nowDenver );
System.out.println( "nowCalifornia: " + nowCalifornia );
When run…
运行时…
nowDenver: 2013-11-21T18:12:49.372-07:00
nowCalifornia: 2013-11-21T17:12:49.372-08:00
About Joda-Time…
关于乔达时间…
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
// About Daylight Saving Time (DST): https://en.wikipedia.org/wiki/Daylight_saving_time
// Time Zone list: http://joda-time.sourceforge.net/timezones.html
回答by Chris Alderson
I had to a similar issue myself recently, and setting the timezone to a locale worked better for me (i.e. not EST/EDT, but America/New_York). I tried EST then tried to do the daylight savings time offset stuff for EDT and this turned out to be a heck of lot easier. Set your timezone to whatever you want it to be then make use of the Date object to create a new date and it will for that timezone. Then you can use the format method to take a timestamp however you please.
我最近自己也遇到了类似的问题,将时区设置为语言环境对我来说效果更好(即不是 EST/EDT,而是 America/New_York)。我尝试了 EST,然后尝试为 EDT 做夏令时偏移的事情,结果证明这要容易得多。将您的时区设置为您想要的任何内容,然后使用 Date 对象创建一个新日期,它将用于该时区。然后你可以使用 format 方法来获取时间戳。
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
Date date = new Date();
timeStamp = date.format('yyyy-MM-dd HH:mm:ss.SSSZ');
System.out.println(timeStamp);
Returns
退货
"2019-07-25 17:09:23:626-0400"
回答by Basil Bourque
tl;dr
tl;博士
ZonedDateTime
.now(
ZoneId.of( "America/Los_Angeles" )
)
See this code run live at IdeOne.com. (Be aware the system clock on that site seems to be about a half-hour slow today.)
查看此代码在 IdeOne.com 上实时运行。(请注意,该站点上的系统时钟今天似乎慢了大约半小时。)
zdt.toString(): 2019-07-27T12:29:42.029531-07:00[America/Los_Angeles]
zdt.toString(): 2019-07-27T12:29:42.029531-07:00[美国/洛杉矶]
java.time
时间
The modern approach uses the java.timeclasses built into Java 8 and later, defined in JSR 310.
现代方法使用Java 8 及更高版本中内置的java.time类,在 JSR 310 中定义。
I am in MST and I want my Date in PST. I set the timeZone that I want.
我在 MST,我希望我的日期在 PST。我设置了我想要的时区。
Never depend on the current default time zone of the JVM at runtime. As a programmer, you have no control over that default. So the results of your code may vary unexpectedly.
永远不要在运行时依赖 JVM 的当前默认时区。作为程序员,您无法控制该默认值。所以你的代码的结果可能会出乎意料地变化。
Always specify the optional time zone arguments to date-time methods.
始终为日期时间方法指定可选的时区参数。
Now if i do c.getTime() I always get my server time.
现在,如果我执行 c.getTime() 我总能得到我的服务器时间。
Learn to think not of client-time or server-time, but rather UTC. Most of your business logic, data storage, data exchange, and logging should be done in UTC. Think of UTC as the One True Time?, and all other offsets/zones are but mere variations.
学会不考虑客户端时间或服务器时间,而是考虑 UTC。您的大部分业务逻辑、数据存储、数据交换和日志记录都应在 UTC 中完成。将 UTC 视为唯一的真实时间?所有其他偏移/区域都只是变化。
For UTC, use Instant
.
对于 UTC,请使用Instant
.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Generate text representing that moment in standard ISO 8601 format.
以标准 ISO 8601 格式生成表示该时刻的文本。
String output = instant.toString() ;
Instead I want Pacific Date time. Please help How to get the date time Object in the specified timezone.
相反,我想要太平洋日期时间。请帮助如何获取指定时区中的日期时间对象。
None of your terms (Pacific
, MST
, or PST
) are true time zones.
您的所有术语 ( Pacific
、MST
或PST
) 都不是真正的时区。
Specify a proper time zone namein the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。永远不要使用 2-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。Continent/Region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
ZoneId z = ZoneId.of( "America/Montreal" ) ;
To adjust from UTC to a time zone, apply a ZoneId
to get a ZonedDateTime
.
要将 UTC 调整为时区,请应用 aZoneId
以获取ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Edmonton" ) ; // https://time.is/Edmonton
ZonedDateTime zdt = instant.atZone( z ) ;
And try one of the time zones on the west coast of North America.
并尝试北美西海岸的时区之一。
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ; // https://time.is/Los_Angeles
ZonedDateTime zdt = instant.atZone( z ) ;
To generate strings in formats other than ISO 8601, use the DateTimeFormatter
class. Search Stack Overflow as this has been covered many many times already.
要以 ISO 8601 以外的格式生成字符串,请使用DateTimeFormatter
该类。搜索堆栈溢出,因为这已经被多次覆盖。
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
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
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。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Most of the java.timefunctionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.timeclasses.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10、Java SE 11及更高版本 - 标准 Java API 的一部分,具有捆绑实现。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 大部分java.time功能在ThreeTen-Backport中向后移植到 Java 6 & 7 。
- 安卓
- 更高版本的 Android 捆绑实现java.time类。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
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
,和更多。