4

I am trying to calculate time difference given a start datetime and end datetime. I have 2 date objects to calculate the time difference. The issue is when the dates span across a DST day (eg:- Nov 7th).

start datetime = Nov 6th, 16:30

end datetime = Nov 7th, 01:00

Expected difference = 8.5 hours, but received 9.5 hours

Using Luxon JS Library

<script src="https://cdn.jsdelivr.net/npm/luxon@1.25.0/build/global/luxon.min.js"></script>
<script>
startDate = luxon.DateTime.fromObject({year: 2021, month: 11, day: 06, hour: 16, minute: 30 }, { zone: 'America/New_York' });
endDate = luxon.DateTime.fromObject({year: 2021, month: 11, day: 07, hour: 01, minute: 0 }, { zone: 'America/New_York' });

diff = Math.abs(startDate.diff(endDate).as('hours'));
console.log(startDate.toMillis() + ' ' + endDate.toMillis() + ' ' + diff)
</script>

The above code gives me 570 which is 9.5 hours. I am expecting 510 which is 8.5 hours using the diff function.

I can use the offset on each of these dates to plus the offset difference

offset=(endDate.offset - startDate.offset)/60
console.log(endDate.diff(startDate, 'hours').plus({hours: offset}).toObject())

I wanted to know if there is another way to solve this using the diff method.

PackedUp
  • 369
  • 5
  • 16
  • 4
    The following doesn't answer your question, it just helps explain why it happens. In New York on 7 Nov 2021, the time 01:00 occurred twice. Typically functions will select the second occurrence, not the first. The proposed [*Temporal* object](https://github.com/tc39/proposal-temporal) allows a choice, see [*Time Zones and Resolving Ambiguity*](https://tc39.es/proposal-temporal/docs/ambiguity.html). – RobG Nov 10 '21 at 09:05
  • 3
    In relation to the above ambiguity, Luxon makes no promise as to which 1 am it will use, see its [documentation for *ambiguous times*](https://github.com/moment/luxon/blob/master/docs/zones.md#ambiguous-times). There is also [*Math across DSTs*](https://github.com/moment/luxon/blob/master/docs/zones.md#math-across-dsts). – RobG Nov 10 '21 at 09:10
  • 1
    I had a relevant, but different, issue. In your case, I couldn't actually reproduce it, I get `8.5` as you expected. See console here: https://jsfiddle.net/7Lwejxyh/ – Paul Oct 22 '22 at 17:32

0 Answers0