Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading