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

尝试给对象属性赋值为当前日期时结果变为明日日期问题咨询

问题原因
  • 时区不匹配:JavaScript 直接调用new Date()生成的是运行环境的本地时区时间,但你的数据中disabledOn字段存储的是带Z后缀的UTC标准时间。如果你所处时区比UTC早(比如中国属于UTC+8时区),当本地时间处于下午16点之后,对应UTC时间就会进入次日:比如东八区2024-05-20 20:00的本地时间,转成UTC时间就是2024-05-21 00:00,存入数据库后自然显示为明日日期。
  • 赋值逻辑未对齐日期零点:你直接把当前完整时间赋值给disabledOn,就算时区匹配,存入的也只是当前时刻而不是当日零点,不过这不是跨天的核心诱因。
解决方法
  • 方案1:统一使用UTC时间处理,赋值时对齐到UTC当日零点
// 生成UTC时区的当日零点时间
const now = new Date();
const utcToday = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));

let credentials = await this.Model.findCredentialsByAid(user.aid, true)
if (!credentials || credentials.length == 0) {
  credentials = await this.Model.findCredentialsByUserId(user._id)
}

// 遍历修改原对象用forEach语义更准确,不需要用map
credentials.forEach((credential: any) => {
  if (credential.credentialType === CredentialType.oneTimeToken) {
    if (!(credential.disabledOn < utcToday)) {
      credential.disabledOn = utcToday;
      console.log(credential);
    }
  }
})
  • 方案2:统一使用本地时区处理,将本地当日零点转成UTC时间再存储,避免跨天
const now = new Date();
// 生成本地时区的当日零点
const localToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
// 转换为对应的UTC时间,避免存储时跨天
const storedToday = new Date(localToday.getTime() - (now.getTimezoneOffset() * 60 * 1000));

// 后续判断和赋值都使用storedToday即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:09:03