我正在尝试将 UTC 的长时间戳转换为东部标准时间并且完全迷路了。任何提示都会很棒!
谢谢,R
试试这个:
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 的解决方案AnInstant
代表时间线上的一个瞬时点。它独立于时区。为了在时区中表示它,您可以使用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
输出中的 是零时区偏移的时区指示符。它代表 Zulu 并指定Etc/UTC
时区(时区偏移量为+00:00
小时)。
注意:无论出于何种原因,如果您需要将此对象转换Instant
为 的对象java.util.Date
,您可以执行以下操作:
Date date = Date.from(instant);
从Trail: Date Time了解有关现代日期时间 API *的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,则可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目和 Android API 工作level 仍然不符合 Java-8,请检查Java 8+ APIs available through desugaring和How to use ThreeTenABP in Android Project。