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:00translates 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, matchinggetUTCHours(). 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
TZand value set to a timezone that uses +01:00 (e.g.,Europe/ParisorEurope/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.
- Go to your Lambda function's configuration, add an environment variable with key
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-tzorluxoninstead of relying on the nativeDateobject. For example, withdate-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
- If you need more control over timezones (especially if dealing with multiple timezones), use a library like
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
相关产品推荐
相关产品推荐

