1

I have the following function:

function subtractDatesMs(date1, date2) {
    var departureDate = new Date(date1);
    var arriveDate = new Date(date2);
    var diff = (arriveDate.getTime() - departureDate.getTime());
    return diff;
}

The dates sent as parameters are like this:

"2015-11-09T15:50:00-04:00",
"2015-11-09T12:40:00-05:00"

including timezone offset value.

It works fine in most of the cases, however when I subtract some dates from a region/area where are using daylight time saving the difference is incorrect (it is delayed/ahead 1 hour for example).

What is the best way to subtract these dates and get the correct difference in milliseconds considering daylight time savings from the region/area of the timezone it comes?

Any sample is welcomed. You can use jquery if you want or any other library to get the correct values.

Alberto Montellano
  • 5,886
  • 7
  • 37
  • 53

1 Answers1

3

I think the problem is in the date strings that your code is receiving. The UTC offset should properly reflect the additional DST offset. The example time you gave "2015-11-09T12:40:00-05:00" implies Eastern Standard Time* because of the -05:00. The other example time "2015-11-09T15:50:00-04:00" implies Atlantic Standard Time or Eastern Daylight Time (i.e. Eastern Standard plus DST)

JavaScript's Date object will properly convert the network time formats that you gave in the example.

If it is not possible to correct the input times, you will then need to also know the country since DST is specific to a country or region of a country. You can then use a solution like in the answer given for How to know whether a country is using Daylight Saving Time using JavaScript?, which retrieves the correct timezone offset for a given place or latitude & longitude.

* = This assumes North America

Community
  • 1
  • 1
Ed Ballot
  • 3,405
  • 1
  • 17
  • 24
  • thanks for your answer. Does it mean I need to consume an external API to get the DST for a country? – Alberto Montellano Aug 02 '15 at 16:29
  • 1
    @AlbertoMontellano - No, it means that your input values should *already* account for DST, and therefore there is nothing more to be done. If someone sends you the wrong values, that is to be fixed on their end - not yours. – Matt Johnson-Pint Aug 02 '15 at 23:03