-1

I used the Datediff function to get the difference between dates in minutes.

My problem is that I cannot display the result in the following hh: mm format.

Right now it's like 0: 3, the value I get is 3 minutes, I intend to 00:03.

COMPONENT

 var sec_num = self.Minutes  //self minutes = 3 minutes;
        var hours = Math.floor(sec_num / 60);
        var minutes = Math.floor(sec_num - hours * 60);
        self.display = hours + ":" + minutes ;
        return self.display;

HTML

<span>{{display}}</span>

Stackblitz

Paul sk
  • 293
  • 3
  • 13
  • Do you have moment js library? – Siddharth Pal Dec 16 '19 at 16:44
  • @SiddharthPal yes – Paul sk Dec 16 '19 at 16:45
  • [This](https://stackoverflow.com/questions/5539028/converting-seconds-into-hhmmss) can help. Even [this](https://stackoverflow.com/questions/46055278/format-number-of-seconds-as-mmss-in-angular-2) or [this](https://stackoverflow.com/questions/52321653/angular-datepipe-convert-seconds-to-time-with-zero-timezone). – Nicholas K Dec 16 '19 at 16:50

2 Answers2

1

Use Angular's DatePipe: https://angular.io/api/common/DatePipe

Stackblitz: https://stackblitz.com/edit/angular-nebuv9

{{display | date: 'hh:mm' }}
<br>
{{display | date: 'hh:mm:ss' }}
<br>
{{display | date: 'dd/MM/yyyy hh:mm:ss' }}

2nd solution based on your comments:

https://stackblitz.com/edit/angular-bx6tg5?file=src/app/app.component.ts

self.display = hours + ":" + ('0' + minutes).slice(-2);

Try it with other values than 3 minutes.

Kari F.
  • 1,214
  • 10
  • 16
  • The datepipe doesn't work the way I get the minutes ... I only get a 3 and the format is 0: 3 :( – Paul sk Dec 16 '19 at 18:02
  • If display is a Date then it'll work: `display: Date = new Date(0, 0, 0, 0, 3, 0, 0);` then `{{display | date: 'mm:ss' }}`. I updated the Stackblitz. – Kari F. Dec 16 '19 at 18:24
  • I tested but it didn't work :( I updated the post and put the Stackblitz link to see the code and test. Thanks for trying to help me – Paul sk Dec 16 '19 at 20:55
  • This case works well in the example, the problem is that I will not always receive the value of 3 minutes, I can receive 2 hours and 15 minutes for example and then it will no longer work – Paul sk Dec 16 '19 at 21:32
  • If you don´t want to convert "display" to a Date object you can just format the string as you want. I added another Stackblitz base on your example. – Kari F. Dec 16 '19 at 21:51
0

You can use moment js to format as below

console.log(moment({"minutes": 3}).format('HH:mm'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
Siddharth Pal
  • 1,408
  • 11
  • 23
  • Is there another solution without daring moment.js? I updated the post and put the Stackblitz link to see the code and test. Thanks for trying to help me – Paul sk Dec 16 '19 at 20:56