Skip to content Skip to sidebar Skip to footer

Moment.js Diff Date Formatting

I'm using moment.js and want to calculate the difference between two timestamp,format them afterwards and display them in a div. var diffTime = moment(1390310146.791877).diff( 139

Solution 1:

moment.duration should be used

   let startTime = moment('09:45:20', 'h:mm:ss A').format("HH:mm:ss");
   let endTime = moment('10:30:35', 'h:mm:ss A').format("HH:mm:ss")
   var todayDate = moment(new Date()).format("MM-DD-YYYY"); //Can change, based on the requirement
   var startDate = new Date(`${todayDate} ${startTime}`);
   var endDate = new Date(`${todayDate} ${endTime}`);
   var diffTime = moment(endDate).diff(startDate);

   var duration = moment.duration(diffTime);
   var years = duration.years(),
    days = duration.days(),
    months = duration.months(),
    hrs = duration.hours(),
    mins = duration.minutes(),
    secs = duration.seconds();

var div = document.createElement('div');
div.innerHTML = years + ' years ' + months + 'months ' + days + ' days ' + hrs + ' hrs ' + mins + ' mins ' + secs + ' sec';
document.body.appendChild(div);

jsfiddle


Solution 2:

try this

var diffTime = moment(moment(1390310146.791877).diff( 1390309386.271075)).format('H m s');

it will output "5 30 0"

Edit

here is the simple way to get the difference. for this both the time should be in the same timezone.

var a = moment(1390310146.791877);
var b = moment(1390309386.271075);
a.diff(b)//To get the difference in milliseconds
a.diff(b,'seconds')//To get the difference in seconds
a.diff(b,'minutes')//To get the difference in minutes 
a.zone()//Get the timezone offset in minutes

hope this helps.


Post a Comment for "Moment.js Diff Date Formatting"