Compare UK EndDate with UTC current time?

Viewed 104

How do I convert UK endDate to UTC so that I can compare with UTC current time (nowTime) on node? or is it better to do it other way around? convert current UTC time to London timezone and then do a comparison with UK endDate

For example:

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')
}
2 Answers

Since your local time is UK time this should work othewise you will have to count for the 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)

Since you also tagged momentjs, this is the alternative solution with 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')

For the actual now time, you can omit the date string

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

Or if you want semantically equivalent to nowTime >= endDate

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

Note that for now, we don't need to pass the timezone explicitly. But if you want an object with UTC timezone you can use

const nowInUTC = moment.utc()
Related