0

I want calculate duration Between 2 date in TypseScript (Angular): 2021-11-19 21:59:59 and 2021-11-19 22:00:18

let startdDate: Date = new Date(start);
  let endDate: Date = new Date(end);
  if(end!=null) {
    let duration = new Date(endDate.getTime() - startdDate.getTime());
    return duration.getHours() + ":" +  duration.getMinutes() + ":" + duration.getSeconds();
  } else {
    return "";
  }

but my result is wrong: 1:0:19.

I want 00:00:19

EDIT

I try this but result is wrong again: 01:00:19

const datepipe: DatePipe = new DatePipe('en-US')
let formattedDate = datepipe.transform(duration, 'HH:mm:ss')
Stéphane GRILLON
  • 11,140
  • 10
  • 85
  • 154
  • Check this out https://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript and https://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript – Maksat Rahmanov Nov 22 '21 at 10:37
  • @MaksatRahmanov, is it a javascript (not typescrit). And in my case I have one hour of error. – Stéphane GRILLON Nov 22 '21 at 10:41
  • Have you tried `return duration.getUTCHours() + ":" + duration.getUTCMinutes() + ":" + duration.getUTCSeconds()` ? – GOTO 0 Nov 22 '21 at 10:54
  • @GOTO0, your solution work but with this result: `0:0:19`. is it possible format to `00:00:19` ? – Stéphane GRILLON Nov 22 '21 at 11:04

1 Answers1

1

You can return the time value of date using toLocaleTimeString() function this will return only time according to region. Here you can find documentation.

So in code just change the return statement to this

return duration.toLocaleTimeString([], {
   timeZone: 'UTC',
});
joka00
  • 2,357
  • 1
  • 10
  • 27