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

Lambda中Date对象getHours()返回值晚1小时的问题排查

Why does getHours() return 13 instead of 14 for 2018-05-29T14:00:00+01:00 in AWS Lambda?

Let's break down what's happening here step by step:

The Core Issue: Timezone Mismatch in Lambda

First, let's clarify the time values:

  • Your input time string 2018-05-29T14:00:00+01:00 translates to 13:00 UTC (since +01:00 is one hour ahead of UTC).
  • AWS Lambda's Node.js runtime defaults to UTC timezone, regardless of any timezone labels you see in console timestamps (like the (+01:00) in your Lambda time display—this is just the console converting UTC to your local viewing timezone, not the actual runtime timezone).

Why getHours() and getUTCHours() Both Return 13

  • getUTCHours() returns the hour in UTC time, which is correctly 13 here—this is expected behavior.
  • getHours() returns the hour in the runtime's local timezone. Since Lambda runs in UTC by default, this also returns 13, matching getUTCHours(). That's why you're seeing the same result for both methods.

How to Fix This Without Manually Adding 1 Hour

You have two clean options to get the expected 14 hour value:

  • Set the Lambda runtime timezone via environment variable

    • Go to your Lambda function's configuration, add an environment variable with key TZ and value set to a timezone that uses +01:00 (e.g., Europe/Paris or Europe/London—note that some timezones observe daylight saving, so pick one that matches your use case).
    • Once set, getHours() will return the hour in that timezone, so your input time will correctly show 14.
  • Use a timezone-aware date library

    • If you need more control over timezones (especially if dealing with multiple timezones), use a library like date-fns-tz or luxon instead of relying on the native Date object. For example, with date-fns-tz:
      const { utcToZonedTime } = require('date-fns-tz');
      const timeStr = '2018-05-29T14:00:00+01:00';
      const targetTimeZone = 'Europe/Paris';
      const zonedDate = utcToZonedTime(new Date(timeStr), targetTimeZone);
      console.log(zonedDate.getHours()); // Will log 14
      

Key Takeaway

The console's displayed timezone for Lambda timestamps doesn't reflect the runtime's actual timezone. Lambda runs in UTC by default, which is why your native Date methods are returning UTC-aligned hours. Fixing this either via the TZ environment variable or a timezone library will give you the expected value without manual hacks.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:42:16