java Java中格林威治标准时间的毫秒数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17472989/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:06:25  来源:igfitidea点击:

Milliseconds to Date in GMT in Java

javaandroiddate

提问by Michal

I need to covert milliseconds to GMT date (in Android app), example:

我需要将毫秒转换为 GMT 日期(在 Android 应用程序中),例如:

1372916493000

1372916493000

When I convert it by this code:

当我用这段代码转换它时:

Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(millis);
Date date = cal.getTime();

the result is 07:41 07/04/2013. The result is the same when I use just:

结果是07:41 07/04/2013。当我只使用时,结果是一样的:

Date date = new Date(millis);

Unfortunately the result looks incorrect, it looks like my local time. I tried to convert the same number by this serviceand the result is 05:41 07/04/2013, which I believe is correct. So I have two hours difference. Anybody has any suggestion / tips what's wrong with my conversion?

不幸的是,结果看起来不正确,它看起来像我的当地时间。我试图通过此服务转换相同的数字,结果是05:41 07/04/2013,我认为这是正确的。所以我有两个小时的差异。有人有任何建议/提示我的转换有什么问题吗?

回答by Evgeniy Dorofeev

If result which looks incorrect means System.out.println(date)then it's no surprise, because Date.toStringconverts date into string representation in local timezone. To see result in GMT you can use this

如果结果看起来不正确意味着System.out.println(date)那么这并不奇怪,因为Date.toString将日期转换为本地时区的字符串表示形式。要在 GMT 中查看结果,您可以使用它

SimpleDateFormat df = new SimpleDateFormat("hh:ss MM/dd/yyyy");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String result = df.format(millis);

回答by Basil Bourque

tl;dr

tl;博士

Instant.ofEpochMilli( 1_372_916_493_000L )         // Moment on timeline in UTC.

2013-07-04T05:41:33Z

2013-07-04T05:41:33Z

…and…

…和…

Instant.ofEpochMilli( 1_372_916_493_000L )          // Moment on timeline in UTC.
       .atZone( ZoneId.of( "Europe/Berlin" ) )  // Same moment, different wall-clock time, as used by people in this region of Germany.

2013-07-04T07:41:33+02:00[Europe/Berlin]

2013-07-04T07:41:33+02:00[欧洲/柏林]

Details

细节

You are using troublesome old date-time classes now supplanted by the java.timeclasses.

您正在使用麻烦的旧日期时间类,现在已被java.time类取代。

java.time

时间

If you have a count of milliseconds since the epoch reference date of first moment of 1970 in UTC, 1970-01-01T00:00Z, then parse as an Instant. The Instantclass represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).

如果您计算了自 UTC 中 1970 年第一时刻的纪元参考日期 1970-01-01T00:00Z 以来的毫秒数,则解析为Instant. 该Instant级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。

Instant instant = Instant.ofEpochMilli( 1_372_916_493_000L ) ;

instant.toString(): 2013-07-04T05:41:33Z

Instant.toString(): 2013-07-04T05:41:33Z

To see that same simultaneous moment through the lens of a particular region's wall-clock time, apply a time zone (ZoneId) to get a ZonedDateTime.

要通过特定区域挂钟时间的镜头查看同一时刻,请应用时区 ( ZoneId) 以获取ZonedDateTime.

ZoneId z = ZoneId.of( "Europe/Berlin" ) ; 
ZonedDateTime zdt = instant.atZone( z ) ;

zdt.toString(): 2013-07-04T07:41:33+02:00[Europe/Berlin]

zdt.toString(): 2013-07-04T07:41:33+02:00[欧洲/柏林]



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

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式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 类?

回答by dumbfingers

It seemed you were messed up with your home timezone and the UTC timezone during the conversion.

在转换过程中,您似乎弄乱了您的家庭时区和 UTC 时区。

Let's assume you are in London(currently London has 1 hour ahead of GMT) and the milliseconds is the time in your home timezone(in this case, London).

让我们假设你在伦敦(伦敦目前有格林威治时间1个小时)和毫秒是在你家时区的时间(在这种情况下,伦敦)。

Then, you probably should:

那么,你可能应该:

Calendar cal = Calendar.getInstance();
// Via this, you're setting the timezone for the time you're planning to do the conversion
cal.setTimeZone(TimeZone.getTimeZone("Europe/London"));
cal.setTimeInMillis(1372916493000L);
// The date is in your home timezone (London, in this case)
Date date = cal.getTime();


TimeZone destTz = TimeZone.getTimeZone("GMT");
// Best practice is to set Locale in case of messing up the date display
SimpleDateFormat destFormat = new SimpleDateFormat("HH:mm MM/dd/yyyy", Locale.US);
destFormat.setTimeZone(destTz);
// Then we do the conversion to convert the date you provided in milliseconds to the GMT timezone
String convertResult = destFormat.parse(date);

Please let me know if I correctly get your point?

请让我知道我是否正确理解你的观点?

Cheers

干杯

回答by Dennis Kriechel

try this

试试这个

public class Test{
    public static void main(String[] args) throws IOException {
        Test test=new Test();
        Date fromDate = Calendar.getInstance().getTime();
        System.out.println("UTC Time - "+fromDate);
        System.out.println("GMT Time - "+test.cvtToGmt(fromDate));
    }
    private  Date cvtToGmt( Date date )
        {
           TimeZone tz = TimeZone.getDefault();
           Date ret = new Date( date.getTime() - tz.getRawOffset() );

           // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
           if ( tz.inDaylightTime( ret ))
           {
              Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

              // check to make sure we have not crossed back into standard time
              // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
              if ( tz.inDaylightTime( dstDate ))
              {
                 ret = dstDate;
              }
           }

           return ret;
        }
}

Test Result:
UTC Time - Tue May 15 16:24:14 IST 2012
GMT Time - Tue May 15 10:54:14 IST 2012

测试结果
UTC 时间 - 5 月 15 日星期二 16:24:14 IST 2012
GMT 时间 - 2012年 5 月 15 日星期二 10:54:14 IST

回答by Tala

Date date = cal.getTime();

Date date = cal.getTime();

returns date created via

返回日期创建通过

public final Date getTime() {
    return new Date(getTimeInMillis());
}

where getTimeInMillis()returns milliseconds without any TimeZone.

wheregetTimeInMillis()返回没有任何 TimeZone 的毫秒。

I would suggest looking here for how to do what you want how-to-handle-calendar-timezones-using-java

我建议在这里寻找如何做你想做的事情how-to-handle-calendar-timezones-using-java