Michael Haren
Michael Haren

Reputation: 108376

How to calculate number of days between two dates?

For example, given two dates in input boxes:

<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>

<script>
  alert(datediff("day", first, second)); // what goes here?
</script>

How do I get the number of days between two dates in JavaScript?

Upvotes: 589

Views: 813249

Answers (30)

marcobiedermann
marcobiedermann

Reputation: 4933

The following solutions will assume these variables are available in the code:

const startDate  = '2020-01-01';
const endDate    = '2020-03-15';

Native JS

Steps:

  1. Set start date
  2. Set end date
  3. Calculate difference
  4. Convert milliseconds to days
const diffInMs   = new Date(endDate) - new Date(startDate);
const diffInDays = diffInMs / (1000 * 60 * 60 * 24);

Comment:

I know this is not part of your questions but in general, I would not recommend doing any date calculation or manipulation in vanilla JavaScript and rather use a library like date-fns, Luxon or moment.js due to many edge cases.

This vanilla JavaScript answer calculates the days as a decimal number. Also, it could run into edge cases when working with Daylight Savings Time


Using a Library

- Date-fns

const differenceInDays = require('date-fns/differenceInDays');
const diffInDays = differenceInDays(new Date(endDate), new Date(startDate));

documentation: https://date-fns.org/v2.16.1/docs/differenceInDays

- Luxon

const { DateTime } = require('luxon');
const diffInDays = DateTime.fromISO(endDate).diff(DateTime.fromISO(startDate), 'days').toObject().days;

documentation: https://moment.github.io/luxon/api-docs/index.html#datetimediff

- Moment.js

const moment = require('moment');
const diffInDays = moment(endDate).diff(moment(startDate), 'days');

documentation: https://momentjs.com/docs/#/displaying/difference/


Examples on RunKit

Upvotes: 133

Tolo Palmer
Tolo Palmer

Reputation: 1780

I would use ceil instead of floor, round will work but it isn't the right operation.

function dateDiff(str1, str2){
    var diff = Date.parse(str2) - Date.parse(str1); 
    return isNaN(diff) ? NaN : {
        diff: diff,
        ms: Math.ceil(diff % 1000),
        s: Math.ceil(diff / 1000 % 60),
        m: Math.ceil(diff / 60000 % 60),
        h: Math.ceil(diff / 3600000 % 24),
        d: Math.ceil(diff / 86400000)
    };
}

Upvotes: 6

Andy
Andy

Reputation: 11502

The elephant in the room is that there's no single right answer!

If you just want the number of 24 hour periods between 2 dates then just subtract them, divide by 86400000, round up or down depending on your personal requirement and you're done.

If you want the number of calendar days it depends what time zone you're in: Say it's 11pm and you're in Bangkok, in 2 hours time it will be a different day for you, but for someone in LA it will be the same day.

Only if you're sure that (a) both the dates you're comparing (b) the timezone of your JavaScript instance (c) the person who wants to know the answer, are all in the same time zone, then you can do the calculation using local times.

In all other cases you need to think more carefully about what you're trying to achieve. For instance if one of the input dates is in Bangkok and the other is in LA then the number of days difference could still be 1 even if the two input values are identical.

In my case I don't know the time zone of either or the input dates or the person who's reading the output, so I decided to calculate what the number of calendar days would be in UTC like this:

(
    Date.UTC(d1.getUTCFullYear(), d1.getUTCMonth(), d1.getUTCDate()) 
    -
    Date.UTC(d2.getUTCFullYear(), d2.getUTCMonth(), d2.getUTCDate())
) / 86400000

Upvotes: 0

fuentesjr
fuentesjr

Reputation: 52358

I would go ahead and grab this small utility and in it you will find functions to this for you. Here's a short example:

        <script type="text/javascript" src="date.js"></script>
        <script type="text/javascript">
            var minutes = 1000*60;
            var hours = minutes*60;
            var days = hours*24;

            var foo_date1 = getDateFromFormat("02/10/2009", "M/d/y");
            var foo_date2 = getDateFromFormat("02/12/2009", "M/d/y");
            
            var diff_date = Math.round((foo_date2 - foo_date1)/days);
            alert("Diff date is: " + diff_date );
        </script>

Upvotes: 44

bookworm
bookworm

Reputation: 51

The easiest answer, accounting for time of day and leap years, boils down to five lines of code. You only need three lines of code if know that your entries will never have a time component.

  date1 = new Date("1/1/2000");
  date2 = new Date("1/1/2001");
  date1.setHours(0, 0, 0, 0); // this line accounts for date strings that have time components
  date2.setHours(0, 0, 0, 0); // this too
  daysBetween = Math.round((date2 - date1) / (24 * 60 * 60 * 1000));

I've included a fully documented function called daysDiff that accepts JavaScript date objects and throws errors if the parameters are malformed.

/**
 * Calculate the number of days between two dates, taking into account possible leap years.
 * Returns a positive or negative integer.
 *
 * @param {Date} date1 - The earlier of the two dates.
 * @param {Date} date2 - The later of the two dates.
 * @throws {TypeError} - If either dateOne or dateTwo is not a valid Date object.
 * @returns {number}   - Integer number of days between date1 and date2.
*/
function daysDiff(date1, date2) {
  // Ensure date1 and date2 are valid Date objects
  if (!(date1 instanceof Date) || !(date2 instanceof Date)) {
      throw new TypeError('Both date1 and date2 must be valid Date objects.');
  }

  const millisecondsPerDay = 24 * 60 * 60 * 1000;
  
  // Reset time components to midnight to consistent days between without worrying about times.
  date1.setHours(0, 0, 0, 0);
  date2.setHours(0, 0, 0, 0);
  
  // Calculate the difference in milliseconds and convert to days
  return Math.round((date2 - date1) / millisecondsPerDay);
}

// accounts for leap year
console.log(daysDiff(new Date("1/1/2024"), new Date("4/30/2024")));

// returns the number of days between today and Jan 1, 2023
console.log(daysDiff(new Date("1/1/2023"), new Date()));

// returns a negative number as date1 is bigger than date2
console.log(daysDiff(new Date("1/30/2024"), new Date("1/1/2024")));

// ignores the time component so will return same result any time of day
console.log(daysDiff(new Date("1/30/2024 13:40:00", new Date())));

// throws an error because date1, while true, isn't a date.`
console.log(daysDiff("frogs are great", new Date()));

Upvotes: 1

Lewis Nakao
Lewis Nakao

Reputation: 7372

I took some inspiration from other answers and made the inputs have automatic sanitation. I hope this works well as an improvement over other answers.

I also recommend the use of <input type="date"> fields which would help validate user inputs.

//use best practices by labeling your constants.
let MS_PER_SEC = 1000
  , SEC_PER_HR = 60 * 60
  , HR_PER_DAY = 24
  , MS_PER_DAY = MS_PER_SEC * SEC_PER_HR * HR_PER_DAY
;

//let's assume we get Date objects as arguments, otherwise return 0.
function dateDiffInDays(date1Time, date2Time) {
    if (!date1Time || !date2Time) return 0;
    return Math.round((date2Time - date1Time) / MS_PER_DAY);
}

function getUTCTime(dateStr) {
  const date = new Date(dateStr);
  // If use 'Date.getTime()' it doesn't compute the right amount of days
  // if there is a 'day saving time' change between dates
  return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());
}


function calcInputs() {
  let date1 = document.getElementById("date1")
    , date2 = document.getElementById("date2")
    , resultSpan = document.getElementById("result")
  ;
  if (date1.value && date2.value && resultSpan) {
    //remove non-date characters
    console.log(getUTCTime(date1.value));
    let date1Time = getUTCTime(date1.value)
      , date2Time = getUTCTime(date2.value)
      , result = dateDiffInDays(date1Time, date2Time)
    ;
    resultSpan.innerHTML = result + " days";
  }
}
window.onload = function() { calcInputs(); };

//some code examples
console.log(dateDiffInDays(new Date("1/15/2019"), new Date("1/30/2019")));
console.log(dateDiffInDays(new Date("1/15/2019"), new Date("2/30/2019")));
console.log(dateDiffInDays(new Date("1/15/2000"), new Date("1/15/2019")));
<input type="date" id="date1" value="2000-01-01" onchange="calcInputs();" />
<input type="date" id="date2" value="2022-01-01" onchange="calcInputs();"/>
Result: <span id="result"></span>

Upvotes: 1

trincot
trincot

Reputation: 351128

The daylight saving issue is invalidating quite a few answers here. I would use a helper function to get a unique day number for a given date -- by using the UTC method:

const dayNumber = a => Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()) / (24*60*60*1000);
const daysBetween = (a, b) => dayNumber(b) - dayNumber(a);

// Testing it
const start = new Date(1000, 0, 1); // 1 January 1000
const end   = new Date(3000, 0, 1); // 1 January 3000
let current = new Date(start);
for (let days = 0; current < end; days++) {
    const diff = daysBetween(start, current);
    if (diff !== days) throw "test failed";
    current.setDate(current.getDate() + 1); // move current date one day forward
}
console.log("tests succeeded");

Upvotes: 1

Miles
Miles

Reputation: 32488

Here is a quick and dirty implementation of datediff, as a proof of concept to solve the problem as presented in the question. It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).

/**
 * Take the difference between the dates and divide by milliseconds per day.
 * Round to nearest whole number to deal with DST.
 */
function datediff(first, second) {        
    return Math.round((second - first) / (1000 * 60 * 60 * 24));
}

/**
 * new Date("dateString") is browser-dependent and discouraged, so we'll write
 * a simple parse function for U.S. date format (which does no error checking)
 */
function parseDate(str) {
    var mdy = str.split('/');
    return new Date(mdy[2], mdy[0] - 1, mdy[1]);
}

alert(datediff(parseDate(first.value), parseDate(second.value)));
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>

You should be aware that the "normal" Date APIs (without "UTC" in the name) operate in the local timezone of the user's browser, so in general you could run into issues if your user is in a timezone that you don't expect, and your code will have to deal with Daylight Saving Time transitions. You should carefully read the documentation for the Date object and its methods, and for anything more complicated, strongly consider using a library that offers more safe and powerful APIs for date manipulation.

Also, for illustration purposes, the snippet uses named access on the window object for brevity, but in production you should use standardized APIs like getElementById, or more likely, some UI framework.

Upvotes: 552

Ajay Prajapati
Ajay Prajapati

Reputation: 192

 // JavaScript / NodeJs answer  
   let startDate = new Date("2022-09-19");
   let endDate = new Date("2022-09-26");

   let difference = startDate.getTime() - endDate.getTime();
   
    console.log(difference);

   let TotalDiffDays = Math.ceil(difference / (1000 * 3600 * 24));
   console.log(TotalDiffDays + " days :) ");

Upvotes: 2

nkitku
nkitku

Reputation: 5748

One-Liner and small

const diff=(e,t)=>Math.floor((new Date(e).getTime()-new Date(t).getTime())/1000*60*60*24);

// or

const diff=(e,t)=>Math.floor((new Date(e)-new Date(t))/864e5);

// or

const diff=(a,b)=>(new Date(a)-new Date(b))/864e5|0; 

// use
diff('1/1/2001', '1/1/2000')

For TypeScript

const diff = (from: string, to: string) => Math.floor((new Date(from).getTime() - new Date(to).getTime()) / 86400000);

Upvotes: 7

some
some

Reputation: 49632

The easiest way to get the difference between two dates:

var diff = Math.floor((Date.parse(str2) - Date.parse(str1)) / 86400000);

You get the difference days (or NaN if one or both could not be parsed). The parse date gived the result in milliseconds and to get it by day you have to divided it by 24 * 60 * 60 * 1000

If you want it divided by days, hours, minutes, seconds and milliseconds:

function dateDiff( str1, str2 ) {
    var diff = Date.parse( str2 ) - Date.parse( str1 ); 
    return isNaN( diff ) ? NaN : {
        diff : diff,
        ms : Math.floor( diff            % 1000 ),
        s  : Math.floor( diff /     1000 %   60 ),
        m  : Math.floor( diff /    60000 %   60 ),
        h  : Math.floor( diff /  3600000 %   24 ),
        d  : Math.floor( diff / 86400000        )
    };
}

Here is my refactored version of James version:

function mydiff(date1,date2,interval) {
    var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
    date1 = new Date(date1);
    date2 = new Date(date2);
    var timediff = date2 - date1;
    if (isNaN(timediff)) return NaN;
    switch (interval) {
        case "years": return date2.getFullYear() - date1.getFullYear();
        case "months": return (
            ( date2.getFullYear() * 12 + date2.getMonth() )
            -
            ( date1.getFullYear() * 12 + date1.getMonth() )
        );
        case "weeks"  : return Math.floor(timediff / week);
        case "days"   : return Math.floor(timediff / day); 
        case "hours"  : return Math.floor(timediff / hour); 
        case "minutes": return Math.floor(timediff / minute);
        case "seconds": return Math.floor(timediff / second);
        default: return undefined;
    }
}

Upvotes: 145

borma425
borma425

Reputation: 364

Try This

let today = new Date().toISOString().slice(0, 10)

const startDate  = '2021-04-15';
const endDate    = today;

const diffInMs   = new Date(endDate) - new Date(startDate)
const diffInDays = diffInMs / (1000 * 60 * 60 * 24);


alert( diffInDays  );

Upvotes: 12

MC Emperor
MC Emperor

Reputation: 23037

I recently had the same question, and coming from a Java world, I immediately started to search for a JSR 310 implementation for JavaScript. JSR 310 is a Date and Time API for Java (standard shipped as of Java 8). I think the API is very well designed.

Fortunately, there is a direct port to Javascript, called js-joda.

First, include js-joda in the <head>:

<script
    src="https://cdnjs.cloudflare.com/ajax/libs/js-joda/1.11.0/js-joda.min.js"
    integrity="sha512-piLlO+P2f15QHjUv0DEXBd4HvkL03Orhi30Ur5n1E4Gk2LE4BxiBAP/AD+dxhxpW66DiMY2wZqQWHAuS53RFDg=="
    crossorigin="anonymous"></script>

Then simply do this:

let date1 = JSJoda.LocalDate.of(2020, 12, 1);
let date2 = JSJoda.LocalDate.of(2021, 1, 1);
let daysBetween = JSJoda.ChronoUnit.DAYS.between(date1, date2);

Now daysBetween contains the number of days between. Note that the end date is exclusive.

Upvotes: 2

OhhhThatVarun
OhhhThatVarun

Reputation: 4330

Simple, easy, and sophisticated. This function will be called in every 1 sec to update time.

const year = (new Date().getFullYear());
const bdayDate = new Date("04,11,2019").getTime(); //mmddyyyy

// countdown
let timer = setInterval(function () {

    // get today's date
    const today = new Date().getTime();

    // get the difference
    const diff = bdayDate - today;

    // math
    let days = Math.floor(diff / (1000 * 60 * 60 * 24));
    let hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((diff % (1000 * 60)) / 1000);

}, 1000);

Upvotes: 4

Mamunur Rashid
Mamunur Rashid

Reputation: 1185

This is bit different answer if we want to calculate our age

    {
      birthday: 'April 22, 1993',
      names: {
        first: 'Keith',
        last: 'Buckley'
      }
    },
    {
      birthday: 'January 3, 1975',
      names: {
        first: 'Larry',
        last: 'Heep'
      }
    },
    {
      birthday: 'February 12, 1944',
      names: {
        first: 'Linda',
        last: 'Bermeer'
      }
    }
  ];
const cleanPeople = people.map(function ({birthday, names:{first, last}}) {
      // birthday, age, fullName;
      const now = new Date();
      var age =  Math.floor(( Date.parse(now) - Date.parse(birthday)) / 31536000000);
      return {
        age,
        fullName:`${first} ${last}`
      }
    });
    console.log(cleanPeople);
    console.table(cleanPeople);

Upvotes: -2

Umang Loriya
Umang Loriya

Reputation: 878

Using moment will be much easier in this case, You could try this:

    let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days');

It will give you integer value like 1,2,5,0etc so you can easily use condition check like:

if(days < 1) {

Also, one more thing is you can get more accurate result of the time difference (in decimals like 1.2,1.5,0.7etc) to get this kind of result use this syntax:

let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days', true);

Let me know if you have any further query

Upvotes: 0

Edward
Edward

Reputation: 1100

This answer, based on another one (link at end), is about the difference between two dates.
You can see how it works because it's simple, also it includes splitting the difference into
units of time (a function that I made) and converting to UTC to stop time zone problems.

function date_units_diff(a, b, unit_amounts) {
    var split_to_whole_units = function (milliseconds, unit_amounts) {
        // unit_amounts = list/array of amounts of milliseconds in a
        // second, seconds in a minute, etc., for example "[1000, 60]".
        time_data = [milliseconds];
        for (i = 0; i < unit_amounts.length; i++) {
            time_data.push(parseInt(time_data[i] / unit_amounts[i]));
            time_data[i] = time_data[i] % unit_amounts[i];
        }; return time_data.reverse();
    }; if (unit_amounts == undefined) {
        unit_amounts = [1000, 60, 60, 24];
    };
    var utc_a = new Date(a.toUTCString());
    var utc_b = new Date(b.toUTCString());
    var diff = (utc_b - utc_a);
    return split_to_whole_units(diff, unit_amounts);
}

// Example of use:
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(
   /0|1|2/g, function (x) {return String( d[Number(x)] );} ));

How my code above works

A date/time difference, as milliseconds, can be calculated using the Date object:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

Then to work out the number of seconds in that difference, divide it by 1000 to convert
milliseconds to seconds, then change the result to an integer (whole number) to remove
the milliseconds (fraction part of that decimal): var seconds = parseInt(diff/1000).
Also, I could get longer units of time using the same process, for example:
- (whole) minutes, dividing seconds by 60 and changing the result to an integer,
- hours, dividing minutes by 60 and changing the result to an integer.

I created a function for doing that process of splitting the difference into
whole units of time, named split_to_whole_units, with this demo:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

This answer is based on this other one.

Upvotes: -1

Adelson Silva Couto
Adelson Silva Couto

Reputation: 7

A contribution, for date before 1970-01-01 and after 2038-01-19

function DateDiff(aDate1, aDate2) {
  let dDay = 0;
  this.isBissexto = (aYear) => {
    return (aYear % 4 == 0 && aYear % 100 != 0) || (aYear % 400 == 0);
  };
  this.getDayOfYear = (aDate) => {
    let count = 0;
    for (let m = 0; m < aDate.getUTCMonth(); m++) {
      count += m == 1 ? this.isBissexto(aDate.getUTCFullYear()) ? 29 : 28 : /(3|5|8|10)/.test(m) ? 30 : 31;
    }
    count += aDate.getUTCDate();
    return count;
  };
  this.toDays = () => {
    return dDay;
  };
  (() => {
    let startDate = aDate1.getTime() <= aDate2.getTime() ? new Date(aDate1.toISOString()) : new Date(aDate2.toISOString());
    let endDate = aDate1.getTime() <= aDate2.getTime() ? new Date(aDate2.toISOString()) : new Date(aDate1.toISOString());
    while (startDate.getUTCFullYear() != endDate.getUTCFullYear()) {
      dDay += (this.isBissexto(startDate.getFullYear())? 366 : 365) - this.getDayOfYear(startDate) + 1;
      startDate = new Date(startDate.getUTCFullYear()+1, 0, 1);
    }
    dDay += this.getDayOfYear(endDate) - this.getDayOfYear(startDate);
  })();
}

Upvotes: -1

wj2061
wj2061

Reputation: 6885

I only got two timestamps in millisecond, so I have to do some extra steps with moment.js to get the days between.

const getDaysDiff = (fromTimestamp, toTimestamp) => {
    // set timezone offset with utcOffset if needed
    let fromDate = moment(fromTimestamp).utcOffset(8);
    let toDate = moment(toTimestamp).utcOffset(8);
    // get the start moment of the day
    fromDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
    toDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
    let diffDays = toDate.diff(fromDate, 'days');

    return diffDays;
}

getDaysDiff(1528889400000, 1528944180000)// 1 

Upvotes: -1

Sumit Joshi
Sumit Joshi

Reputation: 1115

A Better Solution by

Ignoring time part

it will return 0 if both the dates are same.

function dayDiff(firstDate, secondDate) {
  firstDate = new Date(firstDate);
  secondDate = new Date(secondDate);
  if (!isNaN(firstDate) && !isNaN(secondDate)) {
    firstDate.setHours(0, 0, 0, 0); //ignore time part
    secondDate.setHours(0, 0, 0, 0); //ignore time part
    var dayDiff = secondDate - firstDate;
    dayDiff = dayDiff / 86400000; // divide by milisec in one day
    console.log(dayDiff);
  } else {
    console.log("Enter valid date.");
  }
}

$(document).ready(function() {
  $('input[type=datetime]').datepicker({
    dateFormat: "mm/dd/yy",
    changeMonth: true,
    changeYear: true
  });
  $("#button").click(function() {
    dayDiff($('#first').val(), $('#second').val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input type="datetime" id="first" value="12/28/2016" />
<input type="datetime" id="second" value="12/28/2017" />
<input type="button" id="button" value="Calculate">

Upvotes: 3

Sriman Pathy
Sriman Pathy

Reputation: 259

The simple way to calculate days between two dates is to remove both of their time component i.e. setting hours, minutes, seconds and milliseconds to 0 and then subtracting their time and diving it with milliseconds worth of one day.

var firstDate= new Date(firstDate.setHours(0,0,0,0));
var secondDate= new Date(secondDate.setHours(0,0,0,0));
var timeDiff = firstDate.getTime() - secondDate.getTime();
var diffDays =timeDiff / (1000 * 3600 * 24);

Upvotes: 4

drzaus
drzaus

Reputation: 25034

Bookmarklet version of other answers, prompting you for both dates:

javascript:(function() {
    var d = new Date(prompt("First Date or leave blank for today?") || Date.now());
    prompt("Days Between", Math.round(
        Math.abs(
            (d.getTime() - new Date(prompt("Date 2")).getTime())
                /(24*60*60*1000)
             )
        ));
})();

Upvotes: -1

stephenbez
stephenbez

Reputation: 5658

I recommend using the moment.js library (http://momentjs.com/docs/#/displaying/difference/). It handles daylight savings time correctly and in general is great to work with.

Example:

var start = moment("2013-11-03");
var end = moment("2013-11-04");
end.diff(start, "days")
1

Upvotes: 132

Michael K
Michael K

Reputation: 832

Using Moment.js

var future = moment('05/02/2015');
var start = moment('04/23/2015');
var d = future.diff(start, 'days'); // 9
console.log(d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>

Upvotes: 17

Norris
Norris

Reputation: 111

Date values in JS are datetime values.

So, direct date computations are inconsistent:

(2013-11-05 00:00:00) - (2013-11-04 10:10:10) < 1 day

for example we need to convert de 2nd date:

(2013-11-05 00:00:00) - (2013-11-04 00:00:00) = 1 day

the method could be truncate the mills in both dates:

var date1 = new Date('2013/11/04 00:00:00');
var date2 = new Date('2013/11/04 10:10:10'); //less than 1
var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates
console.log(daysDiff);

date2 = new Date('2013/11/05 00:00:00'); //1

var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates
console.log(daysDiff);

Upvotes: 11

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93491

Date.prototype.days = function(to) {
  return Math.abs(Math.floor(to.getTime() / (3600 * 24 * 1000)) - Math.floor(this.getTime() / (3600 * 24 * 1000)))
}


console.log(new Date('2014/05/20').days(new Date('2014/05/23'))); // 3 days

console.log(new Date('2014/05/23').days(new Date('2014/05/20'))); // 3 days

Upvotes: 5

Sumit Ridhal
Sumit Ridhal

Reputation: 1419

You can use UnderscoreJS for formatting and calculating difference.

Demo https://jsfiddle.net/sumitridhal/8sv94msp/

 var startDate = moment("2016-08-29T23:35:01");
var endDate = moment("2016-08-30T23:35:01");  
  

console.log(startDate);
console.log(endDate);

var resultHours = endDate.diff(startDate, 'hours', true);

document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(resultHours));
body { white-space: pre; font-family: monospace; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>

Upvotes: 0

function timeDifference(date1, date2) {
  var oneDay = 24 * 60 * 60; // hours*minutes*seconds
  var oneHour = 60 * 60; // minutes*seconds
  var oneMinute = 60; // 60 seconds
  var firstDate = date1.getTime(); // convert to milliseconds
  var secondDate = date2.getTime(); // convert to milliseconds
  var seconds = Math.round(Math.abs(firstDate - secondDate) / 1000); //calculate the diffrence in seconds
  // the difference object
  var difference = {
    "days": 0,
    "hours": 0,
    "minutes": 0,
    "seconds": 0,
  }
  //calculate all the days and substract it from the total
  while (seconds >= oneDay) {
    difference.days++;
    seconds -= oneDay;
  }
  //calculate all the remaining hours then substract it from the total
  while (seconds >= oneHour) {
    difference.hours++;
    seconds -= oneHour;
  }
  //calculate all the remaining minutes then substract it from the total 
  while (seconds >= oneMinute) {
    difference.minutes++;
    seconds -= oneMinute;
  }
  //the remaining seconds :
  difference.seconds = seconds;
  //return the difference object
  return difference;
}
console.log(timeDifference(new Date(2017,0,1,0,0,0),new Date()));

Upvotes: 5

riv
riv

Reputation: 101

It is possible to calculate a full proof days difference between two dates resting across different TZs using the following formula:

var start = new Date('10/3/2015');
var end = new Date('11/2/2015');
var days = (end - start) / 1000 / 60 / 60 / 24;
console.log(days);
// actually its 30 ; but due to daylight savings will show 31.0xxx
// which you need to offset as below
days = days - (end.getTimezoneOffset() - start.getTimezoneOffset()) / (60 * 24);
console.log(days);

Upvotes: 9

NooNa MarJa
NooNa MarJa

Reputation: 545

To Calculate days between 2 given dates you can use the following code.Dates I use here are Jan 01 2016 and Dec 31 2016

var day_start = new Date("Jan 01 2016");
var day_end = new Date("Dec 31 2016");
var total_days = (day_end - day_start) / (1000 * 60 * 60 * 24);
document.getElementById("demo").innerHTML = Math.round(total_days);
<h3>DAYS BETWEEN GIVEN DATES</h3>
<p id="demo"></p>

Upvotes: 12

Related Questions