我正在使用如下所示的 JSON 数据
[
{
"hourly_AQI": 73.0,
"hourly_date": "Tue, 31 Oct 2023 11:00:00 GMT"
},
{
"hourly_AQI": 79.0,
"hourly_date": "Tue, 31 Oct 2023 13:00:00 GMT"
},
{
"hourly_AQI": 77.0,
"hourly_date": "Tue, 31 Oct 2023 14:00:00 GMT"
}
]
我还得到了一个代码,它将创建一个数组,其中 hourly_date 大于本地当前时间。但是当我在 18:03 使用并运行代码时,代码会给我从 13:00:00 开始的时间,结果这是为什么?
const now = new Date();
const filteredData = aqiData?.filter((item) => {
const date = new Date(item.hourly_date);
// Check if the item's date is in the future
return date >= now
});
console.log(filteredData)
我也在下午 1 点左右尝试过,即使我指定了大于或等于的代码,它也会给我提供从上午 7:00 开始的数据。我很困惑请帮忙!
const now = new Date();
const localTimeZone = 'your-time-zone-here';
const formatter = new Intl.DateTimeFormat('en-US', { timeZone: localTimeZone, hour12: false });
const filteredData = aqiData?.filter((item) => {
const date = new Date(item.hourly_date);
const formattedDate = formatter.format(date);
return new Date(formattedDate) >= now;
});
console.log(filteredData);
您可以在进行比较之前将当前的 Date 对象转换为 GMT。 您可以这样做:
const now = new Date();
const nowInGMT = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
const filteredData = aqiData?.filter((item) => {
const date = new Date(item.hourly_date);
// Check if the item's date is in the future
return date >= nowInGMT;
});
console.log(filteredData);