我有一个代表 UTC 时间的 Date 对象。当我使用 getTime() 方法获取该对象的 long 值时,返回的值对应于我们的本地时间(美国中部)。获取与原始 UTC 时间相对应的值的正确方法是什么?
谢谢
该类DateFormat
有一个设置首选 time zone 的方法,并且有一个 time zone 类具有UTC time 的设置。
所以,例如,
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
Date yourUtcDate = sdf.parse(yourOriginalDate);
java.util.Date
没有时区的概念。它只是保持相对于纪元的时间,即 1970 年 1 月 1 日 00:00:00 UTC。Date 是一个模型,与视图分开。当您显示日期时,将应用时区的概念。Date 的 toString() 在默认时区显示人类可读的日期。您可以使用 aDateFormat
在不同的时区(例如 UTC)中显示日期,或者更改 JVM 的默认时区。
getTime()
返回“自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数”,仅此而已(显然,您必须正确创建它)。您可以根据需要对其进行格式化,例如从GregorianCalendar(TimeZone)
构造函数开始。
大多数 Date 类函数已被弃用,因为它们现在在 Calendar 类中转移。
这是从日历获取 UTC 时间的代码。
Date date = new Date(timeStamp);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(date);
这是获取年、月等的示例代码。
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH));
日历还支持许多其他有用的信息,例如 TIME、DAY_OF_MONTH 等。这里列出了所有这些信息。请注意,月份是从 0 开始的。一月是第0个月。
LocalDateTime now = LocalDateTime.now(Clock.systemUTC());
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
Date formattedDate = Date.from(instant);
return formattedDate;