在使用System.currentTimeMillis()
获取当前时间戳时,其返回的时间戳是以UTC时间(世界协调时间)计算的。如果需要将其转换为特定时区的时间,可以通过以下步骤解决:
TimeZone timeZone = TimeZone.getDefault();
TimeZone targetTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); // 例如,设置为东亚时区
int offset = targetTimeZone.getOffset(System.currentTimeMillis()) - timeZone.getOffset(System.currentTimeMillis());
long currentTimeMillis = System.currentTimeMillis() + offset;
这样就可以将System.currentTimeMillis()
获取的时间戳转换为指定时区的时间。需要注意的是,这种方法只能获取当前时间的时间戳,并不能将历史时间或其他时间转换为特定时区的时间。如果需要处理历史时间或其他时间,建议使用java.time
包中的ZonedDateTime
类进行时区转换。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:CurrentTimeMillis时间同步问题如何解决