0

These are my time formats;

const startTime = "20:00";
const endTime = "05:00";
const startDate = "2021-01-20T00:00:00+05:30"
const days = "1"; // it can be 0 also

Now, I need to find the difference between startTime and endTime using moment, and as the "days = 1", it means the endTime ends on the next day:

So the expected output would be,

9hrs 0mints on 2021-01-21

( As the days says 1, we need to count one day and show the endDate and if days=0 means same date as start date )

How to perform this using moment?

As tried I,

var dif = moment.duration(endTime.diff(startTime))

But it gives the error "endTime.diff is not a function". Please help.

Zach
  • 880
  • 5
  • 17

1 Answers1

0

You can use this way when the time duration of more than 24 hours.

var startTime = moment("20:23", "HH:mm");
var endTime = moment("05:10", "HH:mm");
var days ="1";

// calculate the days in milliseconds
var duration = moment.duration(parseInt(days), 'days');
var day = duration.asMilliseconds();

//calculate the total milliseconds
var ms = day + moment(endTime,"HH:mm").diff(moment(startTime,"HH:mm"));
var d = moment.duration(ms);

//get the total duration
var s = Math.floor(d.asHours())+" hrs " + moment.utc(ms).format("mm") + " mins";

console.log(s);
Pulsara Sandeepa
  • 915
  • 10
  • 25
  • Hope, you got my question ! i only have access to startTime and endTime along with "days" ( which means the days at which the time ends, if days=1 means then the endTime will be next day from startDate ) – Christina122 Jan 11 '21 at 04:18
  • Check-in my Edit section in answer, I hope it will solve your question. – Pulsara Sandeepa Jan 11 '21 at 04:46
  • Do we need that seconds ? in var startTime = moment("20:00:00", "HH:mm:ss") ? without seconds will it works ? – Christina122 Jan 11 '21 at 05:09
  • It gives minus value for minutes - ```var startTime = moment("20:23", "HH:mm"); var endTime = moment("05:10", "HH:mm"); ``` try this ! – Christina122 Jan 11 '21 at 05:33
  • Also, it should reduce the hours also - for the above example the time should be - 08:47 minutes ! but it gives 9 hours -13 minutes from your method ! – Christina122 Jan 11 '21 at 05:38
  • @Christina122 sorry for the mistake I have done, now check my new answer, I think it will help you! – Pulsara Sandeepa Jan 11 '21 at 06:01
  • Opps, now you have removed 0 infront of hours ! its outputing as single ( instead of 9 needed 09 ) can you check ? – Christina122 Jan 11 '21 at 06:13
  • You can add a condition for that to check whether `hours<10` and add `0` in front of the answer – Pulsara Sandeepa Jan 11 '21 at 06:36