Home > OS >  Javascript: How to force a date string that is already UTC into UTC?
Javascript: How to force a date string that is already UTC into UTC?

Time:08-17

I have a list of dates (strings) from a delimited text file. All of these times are UTC. E.g 3 seconds past midnight on 1st July UTC

raw_time = 2022-07-01 00:00:03

I have converted this to a date using

my_time = new Date(raw_time)

I wish to test if the dates fall within a range

e.g.

Fri, 01 Jul 2022 00:00:00 GMT

to

Sun, 31 Jul 2022 23:59:59 GMT

The example fails because when I look at

my_time.toUTCString()

I get the result

Thu, 30 Jun 2022 23:00:03 GMT

I should add that I am in the UK on BST (GMT 1)

How can I force the raw date to be converted as a UTC date?

CodePudding user response:

The problem is that your timestamps might be written in UTC timezone, but they are not valid UTC timestamps as per ISO standard: YYYY-MM-DDTHH:mm:ss.sssZ

var myDate = new Date("2022-07-01 00:00:03");
myDate.toUTCString()
//'Thu, 30 Jun 2022 23:00:03 GMT'

var utcDate = new Date("2022-07-01T00:00:03Z"); //note the Z character
utcDate.toUTCString();
//'Fri, 01 Jul 2022 00:00:03 GMT'

The best way to solve the issue would be to update your timestamps file with the correct format. If you for some reason can't, then you can modify the timestamp on the JS side by changing the string:

//raw_time is "2022-07-01 00:00:03"
const formattedTimestamp = raw_time.replace(' ','T').concat('Z')
// formattedTimestamp becomes "2022-07-01T00:00:03Z"

CodePudding user response:

I guess the issue is because your local machine is in GMT Timezone, so when you do new Date(), it gives you Thu, 30 Jun 2022 23:00:03 GMT.

You can use moment timezone, where you can specify the timezone details like Canada, UK. Please refer below: https://momentjs.com/timezone/

Also you can refer to below link: Momentjs: How to convert date/time of one timezone to UTC date/time

Hope this might help.

  • Related