0

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?

Psionman
  • 3,084
  • 1
  • 32
  • 65
  • Isn't the Date object already UTC when you did `my_time = new Date(raw_time)`? When you re-parse to UTC using `.toUTCString()`, you're making the date go 1 hour less as it's the difference between UTC and your locale – Luka Cerrutti Aug 17 '22 at 13:09
  • Would you mind editing the question to include the full code used to compare the date to the desired range? – Mehdi Aug 17 '22 at 13:09
  • Your initial time string is being interpreted in *local* time, not UTC. You should use an ISO-standard time string with the explicit "Z" time zone indicator. (There are other approaches also.) – Pointy Aug 17 '22 at 13:16
  • 1
    Convert it into a valid ISO Date -> `var n = new Date('2022-07-01T00:00:03.000Z')` – Keith Aug 17 '22 at 13:16
  • a UTC date ALWAYS includes a TimeZone information, the GMT indication means a zero TZ. your other dates show no time zone values. – Mister Jojo Aug 17 '22 at 13:20

2 Answers2

2

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"
albjerto
  • 409
  • 2
  • 12
0

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.