【问题标题】:Compare UK EndDate with UTC current time?将 UK EndDate 与 UTC 当前时间进行比较?
【发布时间】:2023-03-18 22:07:01
【问题描述】:

如何将 UK endDate 转换为 UTC,以便与节点上的 UTC 当前时间 (nowTime) 进行比较?还是以其他方式更好?将当前UTC时间转换为伦敦时区,然后与英国endDate进行比较

例如:

const nowTime = new Date('Thu May 10 2020 15:55'); //mock now time in UTC

const date = { //this is london date/time
  EndDate: "2020-05-10",
  EndTime: "15:57",
}

const combineDateTime = date.EndDate + " " + date.EndTime;
const endDate = new Date(combineDateTime).getTime();

if (nowTime >= endDate) {
  console.log('expired');
} else {
  console.log('not expired')
}

【问题讨论】:

  • 你能详细说明一下你如何比较只是日期吗?只有时间?你想要的输出是什么?
  • 比较从 nowTime 到 Endate 的日期和时间。 nowTime > endDate

标签: javascript node.js momentjs


【解决方案1】:

由于您的当地时间是英国时间,这应该可以工作,否则您将不得不计算 dls

 var now = new Date();
var nowTime = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
console.log('UTC (in ms): ' + nowTime.getTime())
nowTimeUTC=nowTime.getTime()

const date = { //this is london date/time via API response
  EndDate: "2020-06-12",
  EndTime: "00:12",
}

servertime=new Date(date.EndDate.concat(" "+date.EndTime))
servertimeinmill=servertime.getTime()
utcoffset=(servertime.getTimezoneOffset()/60)*60*60*1000
servetimeinUTC=servertimeinmill+utcoffset
console.log(servetimeinUTC)
console.log(nowTime>servetimeinUTC)

【讨论】:

  • 谢谢。,这似乎工作。为什么不能使用带有时区的 toLocaleString 来完成它?
  • 它可以用toLocaleString 来完成,但是我不建议在这种情况下使用它,因为它是为了代表时间考虑您选择的语言作为参数,这可能会导致一个大问题,因为LocaleString('en-US') 将在上午/下午显示时间 ex: 01:00 pm 但如果您选择参数 ('it,IT) 它将输出一个字符串表示为 13:00 这可能会导致简单的问题时间计算,但如果您以毫秒为单位计算时间,这应该不是问题
  • 如果我的回答对我有帮助,我将不胜感激考虑支持并接受我的回答
  • 它实际上并没有工作。如果您将 nowTime 更改为 new Date().getTime(); 并将 EndTime 更改为 22:30 - 它应该返回 false。 UTC 中的服务器机器。
  • 你确定 new Date().getTime() 在 UTC 中以毫秒为单位为你提供时间,你能 console.log 告诉我它给你什么吗?
【解决方案2】:

由于您还标记了momentjs,这是moment-timezone 的替代解决方案

const expired = moment.tz('2020-05-10 15:57', 'YYYY-MM-DD hh:mm', 'Europe/London').isSameOrBefore('2020-05-10T15:55:00.000Z')

对于实际的now时间,可以省略日期字符串

const expired = moment.tz('2020-05-10 15:57', 'YYYY-MM-DD hh:mm', 'Europe/London').isSameOrBefore()

或者如果你想在语义上等同于nowTime >= endDate

const expired = moment().isSameOrAfter(moment.tz('2020-05-10 15:57', 'YYYY-MM-DD hh:mm', 'Europe/London'))

请注意,对于now,我们不需要显式传递时区。但是如果你想要一个带有UTC 时区的对象,你可以使用

const nowInUTC = moment.utc()

【讨论】:

  • 谢谢,这个和 Sven.hig 的回答有什么区别?
  • 我的解决方案需要另一个库,如果您不介意另一个依赖项,使用 moment-timezone 使其更具可读性并自动计算夏令时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 2017-05-04
  • 2014-12-25
相关资源
最近更新 更多