[javascript] Get the time difference between two datetimes

I know I can do anything and some more envolving Dates with momentjs. But embarrassingly, I'm having a hard time trying to do something that seems simple: geting the difference between 2 times.

Example:

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

//expected result:
"00:39:30"

what I tried:

var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");

console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
//outputs 10:39:30  

I do not understand what is that "10" there. I live in Brazil, so we are utc-0300 if that is relevant.

The result of moment.duration(now.diff(then)) is a duration with the correct internal values:

 days: 0
 hours: 0
 milliseconds: 0
 minutes: 39
 months: 0
 seconds: 30
 years: 0

So, I guess my question is: how to convert a momentjs Duration to a time interval? I sure can use

duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")

but i feel that there is something more elegant that I am completely missing.

update
looking closer, in the above example now is:

Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}

and moment(moment.duration(now.diff(then))) is:

Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}

I am not sure why the second value is in Daylight Time (-0200)... but I am sure that i do not like dates :(

update 2

well, the value is -0200 probably because 31/12/1969 was a date where the daylight time was being used... so thats that.

This question is related to javascript date time momentjs difference

The answer is


Your problem is in passing the result of moment.duration() back into moment() before formatting it; this results in moment() interpreting it as a time relative to the Unix epoch.

It doesn't give you exactly the format you're looking for, but

moment.duration(now.diff(then)).humanize()

would give you a useful format like "40 minutes". If you're really keen on that specific formatting, you'll have to build a new string yourself. A cheap way would be

[diff.asHours(), diff.minutes(), diff.seconds()].join(':')

where var diff = moment.duration(now.diff(then)). This doesn't give you the zero-padding on single digit values. For that, you might want to consider something like underscore.string - although it seems like a long way to go just for a few extra zeroes. :)


To get the difference between two-moment format dates or javascript Date format indifference of minutes the most optimum solution is

const timeDiff = moment.duration((moment(apptDetails.end_date_time).diff(moment(apptDetails.date_time)))).asMinutes()

you can change the difference format as you need by just replacing the asMinutes() function


If we want only hh:mm:ss, we can use a function like that:

//param: duration in milliseconds
MillisecondsToTime: function(duration) {
    var seconds = parseInt((duration/1000)%60)
        , minutes = parseInt((duration/(1000*60))%60)
        , hours = parseInt((duration/(1000*60*60))%24)
        , days  = parseInt(duration/(1000*60*60*24));

    var hoursDays = parseInt(days*24);
    hours += hoursDays;
    hours = (hours < 10) ? "0" + hours : hours;
    minutes = (minutes < 10) ? "0" + minutes : minutes;
    seconds = (seconds < 10) ? "0" + seconds : seconds;
    return hours + ":" + minutes + ":" + seconds;
}

DATE TIME BASED INPUT

    var dt1 = new Date("2019-1-8 11:19:16");
    var dt2 = new Date("2019-1-8 11:24:16");


    var diff =(dt2.getTime() - dt1.getTime()) ;
    var hours = Math.floor(diff / (1000 * 60 * 60));
    diff -= hours * (1000 * 60 * 60);
    var mins = Math.floor(diff / (1000 * 60));
    diff -= mins * (1000 * 60);


    var response = {
        status : 200,
        Hour : hours,
        Mins : mins
    }

OUTPUT

{
"status": 200,
"Hour": 0,
"Mins": 5
}

If you want difference of two timestamp into total days,hours and minutes only, not in months and years .

var now  = "01/08/2016 15:00:00";
var then = "04/02/2016 14:20:30";
var diff = moment.duration(moment(then).diff(moment(now)));

diff contains 2 months,23 days,23 hours and 20 minutes. But we need result only in days,hours and minutes so the simple solution is:

var days = parseInt(diff.asDays()); //84

var hours = parseInt(diff.asHours()); //2039 hours, but it gives total hours in given miliseconds which is not expacted.

hours = hours - days*24;  // 23 hours

var minutes = parseInt(diff.asMinutes()); //122360 minutes,but it gives total minutes in given miliseconds which is not expacted.

minutes = minutes - (days*24*60 + hours*60); //20 minutes.

Final result will be : 84 days, 23 hours, 20 minutes.


Typescript: following should work,

export const getTimeBetweenDates = ({
  until,
  format
}: {
  until: number;
  format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
  const date = new Date();
  const remainingTime = new Date(until * 1000);
  const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
  const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
  const diff = getUntil.diff(getFrom, format);
  return !isNaN(diff) ? diff : null;
};

I create a simple function with typescript

const diffDuration: moment.Duration = moment.duration(moment('2017-09-04 12:55').diff(moment('2017-09-02 13:26')));
setDiffTimeString(diffDuration);

function setDiffTimeString(diffDuration: moment.Duration) {
  const str = [];
  diffDuration.years() > 0 ? str.push(`${diffDuration.years()} year(s)`) : null;
  diffDuration.months() > 0 ? str.push(`${diffDuration.months()} month(s)`) : null;
  diffDuration.days() > 0 ? str.push(`${diffDuration.days()} day(s)`) : null;
  diffDuration.hours() > 0 ? str.push(`${diffDuration.hours()} hour(s)`) : null;
  diffDuration.minutes() > 0 ? str.push(`${diffDuration.minutes()} minute(s)`) : null;
  console.log(str.join(', '));
} 
// output: 1 day(s), 23 hour(s), 29 minute(s)

for generate javascript https://www.typescriptlang.org/play/index.html


When you call diff, moment.js calculates the difference in milliseconds. If the milliseconds is passed to duration, it is used to calculate duration which is correct. However. when you pass the same milliseconds to the moment(), it calculates the date that is milliseconds from(after) epoch/unix time that is January 1, 1970 (midnight UTC/GMT). That is why you get 1969 as the year together with wrong hour.

duration.get("hours") +":"+ duration.get("minutes") +":"+ duration.get("seconds")

So, I think this is how you should do it since moment.js does not offer format function for duration. Or you can write a simple wrapper to make it easier/prettier.


In ES8 using moment, now and start being moment objects.

const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');

If you want a localized number of days between two dates (startDate, endDate):

var currentLocaleData = moment.localeData("en");
var duration = moment.duration(endDate.diff(startDate));
var nbDays = Math.floor(duration.asDays()); // complete days
var nbDaysStr = currentLocaleData.relativeTime(returnVal.days, false, "dd", false);

nbDaysStr will contain something like '3 days';

See https://momentjs.com/docs/#/i18n/changing-locale/ for information on how to display the amount of hours or month, for example.


Instead of

Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")

It's better to do

moment.utc(total.asMilliseconds()).format("HH:mm:ss");

InTime=06:38,Outtime=15:40

 calTimeDifference(){
        this.start = dailyattendance.InTime.split(":");
        this.end = dailyattendance.OutTime.split(":");
        var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
        var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
        var time3 = ((time2 - time1) / 60);
        var timeHr = parseInt(""+time3);
        var  timeMin = ((time2 - time1) % 60);
    }

EPOCH TIME DIFFERENCE USING MOMENTJS:

To Get Difference between two epoch times:

Syntax: moment.duration(moment(moment(date1).diff(moment(date2)))).asHours()

Difference in Hours: moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asHours()

Difference in minutes: moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asMinutes().toFixed()

Note: You could remove .toFixed() if you need precise values.

Code:

const moment = require('moment')

console.log('Date 1',moment(1590597909877).toISOString())
console.log('Date 2',moment(1590597744551).toISOString())
console.log('Date1 - Date 2 time diffrence is : ',moment.duration(moment(moment(1590597909877).diff(moment(1590597744551)))).asMinutes().toFixed()+' minutes')

Refer working example here: https://repl.it/repls/MoccasinDearDimension


The following approach is valid for all cases (difference between dates less than 24 hours and difference greater than 24 hours):

// Defining start and end variables
let start = moment('04/09/2013 15:00:00', 'DD/MM/YYYY hh:mm:ss');
let end   = moment('04/09/2013 14:20:30', 'DD/MM/YYYY hh:mm:ss');

// Getting the difference: hours (h), minutes (m) and seconds (s)
let h  = end.diff(start, 'hours');
let m  = end.diff(start, 'minutes') - (60 * h);
let s  = end.diff(start, 'seconds') - (60 * 60 * h) - (60 * m);

// Formating in hh:mm:ss (appends a left zero when num < 10)
let hh = ('0' + h).slice(-2);
let mm = ('0' + m).slice(-2);
let ss = ('0' + s).slice(-2);

console.log(`${hh}:${mm}:${ss}`); // 00:39:30

It is very simple with moment below code will return diffrence in hour from current time:

moment().diff('2021-02-17T14:03:55.811000Z', "h")

This will work for any date in the format YYYY-MM-DD HH:mm:ss

const moment=require("moment");
let startDate=moment("2020-09-16 08:39:27");
const endDate=moment();


const duration=moment.duration(endDate.diff(startDate))
console.log(duration.asSeconds());
 console.log(duration.asHours());

Use this,

  var duration = moment.duration(endDate.diff(startDate));

    var aa = duration.asHours();

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') //[days, years, months, seconds, ...]
//Result 1 

Worked for me

See more in http://momentjs.com/docs/#/displaying/difference/


This should work fine.

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);

console.log(d.days() + ':' + d.hours() + ':' + d.minutes() + ':' + d.seconds());

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object

Examples related to momentjs

How to get am pm from the date time string using moment js Vuejs and Vue.set(), update array How to subtract one month using moment.js? Get timezone from users browser using moment(timezone).js Check if date is a valid one moment.js get current time in milliseconds? Deprecation warning in Moment.js - Not in a recognized ISO format Moment js get first and last day of current month Moment get current date Moment.js - How to convert date string into date?

Examples related to difference

Calculate time difference in minutes in SQL Server Java 8: Difference between two LocalDateTime in multiple units Differences between Oracle JDK and OpenJDK Android difference between Two Dates Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C# Get the time difference between two datetimes What is the difference between JVM, JDK, JRE & OpenJDK? What is the difference between bottom-up and top-down? What's the difference between ViewData and ViewBag?