【发布时间】:2010-04-12 19:02:10
【问题描述】:
我正在尝试将 UTC 的长时间戳转换为东部标准时间,但我完全迷路了。任何提示都会很棒!
谢谢, 回复
【问题讨论】:
我正在尝试将 UTC 的长时间戳转换为东部标准时间,但我完全迷路了。任何提示都会很棒!
谢谢, 回复
【问题讨论】:
试试这个:
Date estTime = new Date(utcTime.getTime() + TimeZone.getTimeZone("EST").getRawOffset());
其中 utcTime 是 UTC 时间的 Date 对象(如果您已经有 long 值 - 只需使用它)
【讨论】:
final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("EST"));
c.setTimeInMillis(longTime);
其中longTime 是自 UTC 时间纪元以来的毫秒数。然后您可以使用Calendar 类的方法来获取日期/时间的各个组成部分。
【讨论】:
rd42,你能给我更多的背景信息吗?
您说您有一个“UTC 时间戳”。这是存储在数据库中吗?是字符串吗?
如果您能给出您尝试解决此问题的背景,我或许可以为您提供更多答案。
为了清楚起见,您的意思是您有一个表示 UTC 时间戳的长值。
所以在这种情况下,您要做的是以下内容。
import java.util.Calendar;
import java.util.TimeZone;
TimeZone utcTZ= TimeZone.getTimeZone("UTC");
Calendar utcCal= Calendar.getInstance(utcTZ);
utcCal.setTimeInMillis(utcAsLongValue);
现在你的日历对象是 UTC。
要显示此内容,您需要执行以下操作:
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);
这将允许您读取存储为长值的 UTC 时区的时间戳并将其转换为 Java 日历或日期对象。
希望这能让你到达你需要的地方。
【讨论】:
java.time 现代 API 的解决方案Instant 代表时间线上的一个瞬时点。它独立于时区。为了在时区中表示它,您可以使用Instant#atZone 或ZonedDateTime#ofInstant,如下所示:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// A sample timestamp
long millis = 1620999618896L;
Instant instant = Instant.ofEpochMilli(millis);
System.out.println(instant);
ZonedDateTime zdtET = instant.atZone(ZoneId.of("America/New_York"));
System.out.println(zdtET);
// Alternatively
zdtET = ZonedDateTime.ofInstant(instant, ZoneId.of("America/New_York"));
System.out.println(zdtET);
}
}
输出:
2021-05-14T13:40:18.896Z
2021-05-14T09:40:18.896-04:00[America/New_York]
2021-05-14T09:40:18.896-04:00[America/New_York]
输出中的Z 是零时区偏移的timezone designator。它代表 Zulu 并指定 Etc/UTC 时区(时区偏移量为 +00:00 小时)。
注意:无论出于何种原因,如果您需要将Instant的这个对象转换为java.util.Date的一个对象,您可以这样做:
Date date = Date.from(instant);
通过 Trail: Date Time 了解有关 modern date-time API* 的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。
【讨论】: