Reputation: 1115
I'm just using momentJS for the first time and I love it. However I have been using it for less than a day and I have a problem and I can't seem to find a solution, so perhaps someone here can help. In my Angular application I have a method that takes two dates as timestamps / numbers (sorry if my terminology is wrong) and this should output the difference between these two dates.
I have the following function:
/**
* Method that takes two timestamps and returns the number of hours between the dates
* @param to - timestamp
* @param from - timestamp
*/
public calculateDuration(to: number, from: number): string {
return moment(from).diff(moment(to), 'HHmmss');
}
now suppose I try to call that function like so:
this.calculateDuration(156578488067,1565955844201);
I get an output of -170963523. What I am really looking for is a way for the output to be {{X}} Hours, {{Z}} Minutes and {{Y}} seconds. Using 'HHmmss' isn't correct. But playing around with the different formats listed at https://momentjscom.readthedocs.io/en/latest/moment/04-displaying/01-format/ isn't getting me anywhere. Can someone please help me understand or tell me how I can achieve the desired output using momentJS?
Upvotes: 1
Views: 99
Reputation: 5940
You could subtract directly instead of diff
:
/**
* Method that takes two timestamps and returns the number of hours between the dates
* @param to - timestamp
* @param from - timestamp
*/
function calculateDuration(to, from) {
return moment(to - from).tz('America/New_York').format('HH [Hours,] mm [Minutes and] ss [seconds]');
}
console.log(calculateDuration(156578488067, 1565955844201));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>
Upvotes: 1
Reputation: 13059
Easily done with momentjs
let from = 156578488067,
to = 1565955844201;
let d = moment.duration(to - from);
console.log(`${d.years()} Years ${d.months()} Months ${d.days()} Days ${d.hours()} Hours ${d.minutes()} Minutes ${d.seconds()}.${d.milliseconds()} Seconds`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js" integrity="sha256-H9jAz//QLkDOy/nzE9G4aYijQtkLt9FvGmdUTwBk6gs=" crossorigin="anonymous"></script>
Upvotes: 2