JAVA UTC 到 EST 从长 UTC 时间戳

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

JAVA UTC to EST from a long UTC timestamp

javadatetimeutc

提问by rd42

I'm trying to convert a long timestamp that is UTC to Eastern Standard Time and am totally lost. Any hints would be great!

我正在尝试将 UTC 的长时间戳转换为东部标准时间并且完全丢失了。任何提示都会很棒!

Thanks, R

谢谢,R

回答by duduamar

Try this:

试试这个:

Date estTime = new Date(utcTime.getTime() + TimeZone.getTimeZone("EST").getRawOffset());

Where utcTime is Date object of UTC time (if you already have the long value - just use it)

其中 utcTime 是 UTC 时间的 Date 对象(如果您已经拥有 long 值 - 只需使用它)

回答by Ben S

final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("EST"));
c.setTimeInMillis(longTime);

Where longTimeis the number of milliseconds since the epoch in UTC time. You can then use the methods of the Calendarclass to get the various components of the date/time.

哪里longTime是因为在UTC时间计算历元的毫秒数。然后,您可以使用Calendar类的方法来获取日期/时间的各种组件。

回答by Dave G

rd42, Can you give me a little more context on this?

rd42,你能告诉我更多关于这个的背景吗?

You say you have a "UTC timestamp". Is this stored in a database? Is it a string?

你说你有一个“UTC时间戳”。这是存储在数据库中吗?是字符串吗?

I might be able to provide you more of an answer if you can give the context you're trying to work this in.

如果您能提供您尝试使用的上下文,我可能会为您提供更多答案。



Ok for clarity's sake what you're saying is that you have a long value that represents a timestamp in UTC.

好吧,为了清楚起见,您所说的是您有一个长值,它代表 UTC 中的时间戳。

So in that case what you're going to want to do is the following.

因此,在这种情况下,您要做的是以下操作。

import java.util.Calendar;
import java.util.TimeZone;

TimeZone utcTZ= TimeZone.getTimeZone("UTC");
Calendar utcCal= Calendar.getInstance(utcTZ);
utcCal.setTimeInMillis(utcAsLongValue);

Now you're calendar object is in UTC.

现在你的日历对象是UTC。

To display this though you're going to want to do something like the following:

要显示此内容,您将需要执行以下操作:

import java.text.SimpleDateFormat;
import java.util.Date;

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz");
sdf.setTimeZone(utcTZ);
Date utcDate= utcCal.getTime();
sdf.formatDate(utcDate);

This will allow you to read in a timestamp for the UTC time zone stored as a long value and convert it to a Java Calendar or Date object.

这将允许您读取存储为 long 值的 UTC 时区的时间戳,并将其转换为 Java 日历或日期对象。

Hope that gets you where you need to be.

希望这能让你到达你需要去的地方。