Home > Blockchain >  calculate duration in Typescript (hours, minutes, secondes)
calculate duration in Typescript (hours, minutes, secondes)

Time:11-22

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')

CodePudding user response:

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',
});
  • Related