0

I have the following range that needs to be calculated:

const range = (new Date(endDate) - new Date(startDate))

Where startDate and endDate are: "2020-11-03 17:34:24", "2021-05-06 18:34:1"

How can I convert this to using UTC so that the seconds will remain the same for all browsers?

I was thinking of converting them using Date(startDate).toISOString() then feeding that in the newDate object would that make sense?

lost9123193
  • 10,460
  • 26
  • 73
  • 113

1 Answers1

1

You should ensure that it is in the ECMAScript Date Time String Format (similar to ISO 8601). That means the date and time portions should be separated by a T, and for UTC values it should end with a Z.

In your case, since your input values are like "2020-11-03 17:34:24" and are in terms of UTC, you can do some string manipulation before parsing.

const start = new Date(startDate.replace(' ', 'T').concat('Z'));
const end = new Date(endDate.replace(' ', 'T').concat('Z'));
const seconds = (end - start) / 1000;
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • thanks i'm going to test this now. Out of curiosity, is there a way to add timezone to a date object to do the following? Eg. calculate total sum of seconds from objects from different timezones (some that have daylight savings and some that don't) – lost9123193 Nov 13 '20 at 21:41
  • No. The `Date` object only has one internal value - a Unix Timestamp in terms of milliseconds (UTC-based). It does not store any time zone information. You might consider [Luxon](https://moment.github.io/luxon/) instead. – Matt Johnson-Pint Nov 13 '20 at 22:49