You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java获取PST时区当日起止epoch毫秒结果为UTC的问题

问题描述

需要获取PST时区(对应标准时区IDAmerica/Los_Angeles)当日00:00:00、23:59:59两个时间点对应的epoch毫秒值,代码中已经指定了目标时区,但最终输出的时间戳始终对应UTC时区的当日起止时间,和预期不符。
原有实现代码:

val time_zone = ZoneId.of("America/Los_Angeles")
val today_date = LocalDate.now(time_zone).plusDays(0)
val start_time = today_date + " " + "00:00:00"
val end_time = today_date + " " + "23:59:59"

val date_format = new SimpleDateFormat("yyyy-MM-dd");
val start_millis = date_format.parse(start_time).getTime();
val end_millis = date_format.parse(end_time).getTime();

start_millis

代码运行输出:

res375: Long = 1656460799000

经校验,该时间戳对应UTC时间的00:00,而非America/Los_Angeles时区的当日起始点,不确定是配置遗漏还是依赖版本问题。

问题根因

不需要更新任何依赖,结果错误完全由代码逻辑问题导致:

  • 新旧时间API混用:代码用Java 8+引入的java.time包API(ZoneId、LocalDate)获取目标时区日期,却用老旧的SimpleDateFormat做时间解析,两套API的时区配置完全独立不互通。
  • SimpleDateFormat未绑定目标时区:该类默认使用JVM进程的默认时区执行解析,不会读取你之前定义的time_zone变量,当JVM默认时区为UTC时,自然会计算出UTC时区对应的时间戳。
  • 解析模板与待解析内容不匹配:定义的date_format解析模板为yyyy-MM-dd,但传入的待解析字符串是带时分秒的yyyy-MM-dd HH:mm:ss格式,解析行为本身不符合预期。另外代码中的plusDays(0)属于无意义冗余操作,对结果无任何影响。
正确实现

推荐方案(无兼容问题)

全程使用java.time体系API完成计算,从根源避免时区配置不生效问题,同时可自动适配America/Los_Angeles时区的夏令时切换,比硬编码时区偏移量更准确:

import java.time.{ZoneId, LocalTime}

val targetZone = ZoneId.of("America/Los_Angeles")
val todayInTargetZone = LocalDate.now(targetZone)
// 计算当日00:00:00对应的epoch毫秒值
val startOfDayMillis = todayInTargetZone.atStartOfDay(targetZone).toInstant.toEpochMilli
// 计算当日23:59:59对应的epoch毫秒值
val endOfDayMillis = todayInTargetZone.atTime(LocalTime.of(23, 59, 59))
  .atZone(targetZone).toInstant.toEpochMilli

兼容老旧代码方案

如果因历史原因必须使用SimpleDateFormat,需要同时修正解析模板、手动为格式化类绑定目标时区:

import java.util.TimeZone

val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
dateFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))
val startMillis = dateFormat.parse(start_time).getTime
val endMillis = dateFormat.parse(end_time).getTime

内容的提问来源于stack exchange,提问作者Illustrious Imp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 15:36:26