Comparing two dates with javascript or datejs (date difference)

10,016

Solution 1

If your dates are strings in the common form d/m/y or some variation thereof, you can use:

function toDate(s) {
  var s = s.split('/');
  return new Date(s[2], --s[1], s[0]);
}

You may want to validate the input, or not, depending on how confident you are in the consistency of the supplied data.

Edit to answer comments

To permit different separators (e.g. period (.) or hyphen (-)), the regular expression to split on can be:

  var s = s.split(/[/\.-]/);

The date will be split into date, month and year numbers respectively. The parts are passed to the Date constructor to create a local date object for that date. Since javascript months are zero indexed (January is 0, February is 1 and so on) the month number must be reduced by one, hence --s[1].

/Edit

To compare two date objects (i.e get the difference in milliseconds) simply subtract one from the other. If you want the result in days, then divide by the number of milliseconds in a day and round (to allow for any minor differences caused by daylight saving).

So if you want to see how many days are between today and a date, use:

function diffToToday(s) {
  var today = new Date();
  today.setHours(0,0,0);
  return Math.round((toDate(s) - today) / 8.64e7);
}

alert(diffToToday('2/8/2011')); // -1
alert(diffToToday('2/8/2012')); // 365

PS. The "Finnish" data format is the one used by the vast majority of the world that don't use ISO format dates.

Solution 2

If you are using Datejs, and the optional time.js module, you can run your calculations with the following code by creating a TimeSpan object:

Example

// dd.mm.YYYY or d.m.YYYY
// dd.m.YYYY or d.mm.YYYY

var start = Date.parse("20.09.2011"); 
var end = Date.parse("28.09.2011");

var span = new TimeSpan(end - start);

span.days; // 8

Of course the above could be simplified down to one line if you really want to be extra terse.

Example

new TimeSpan(Date.parse(end) - Date.parse(start)).days; // pass 'end' and 'start' as strings

Hope this helps.

Share:
10,016
Axel Latvala
Author by

Axel Latvala

Aalto University CS Student, like to tinker with electronics and developing all kinds of apps.

Updated on July 19, 2022

Comments

  • Axel Latvala
    Axel Latvala almost 2 years

    I am trying to compare two dates which are in Finnish time form like this: dd.mm.YYYY or d.m.YYYY or dd.m.YYYY or d.mm.YYYY.

    I am having a hard time finding out how to do this, my current code won't work.

    <script src="inc/date-fi-FI.js" type="text/javascript"></script>
    <script type="text/javascript">
        function parseDate() {
            var date = $('#date').val();
            var parsedDate = Date.parse(date);
            alert('Parsed date: '+parsedDate);
        }
        function jämförMedIdag (datum) {
        if (datum == null || datum == "") {
            alert('Inget datum!');
            return;
        }
        /*resultat = Date.compare(Datum1,Datum2);
        alert(resultat); */
        var datum = Date.parse(datum);
        var dagar = datum.getDate();
        var månader = datum.getMonth();
        var år = datum.getYear();
        var nyttDatum = new Date();
        nyttDatum.setFullYear(år,månader,dagar);
        var idag = new Date();
    
        if(nyttDatum>idag) {
            var svar = nyttDatum - idag;
            svar = svar.toString("dd.MM.yyyy");
            alert(svar);
            return(svar);
        } else {
            var svar = idag - nyttDatum;
            svar = svar.toString("dd.MM.yyyy");
            alert(svar);
            return(svar);
        }
    }    
    </script>
    

    This code will try to calculate the difference between two dates, one of them being today. No success lolz.

    Thanks in advance!

    My final code (thanks RobG!):

    function dateDiff(a,b,format) {
        var milliseconds = toDate(a) - toDate(b);
        var days = milliseconds / 86400000;
        var hours = milliseconds / 3600000;
        var weeks = milliseconds / 604800000;
        var months = milliseconds / 2628000000;
        var years = milliseconds / 31557600000;
        if (format == "h") {
            return Math.round(hours);
        }
        if (format == "d") {
            return Math.round(days);
        }
        if (format == "w") {
            return Math.round(weeks);
        }
        if (format == "m") {
            return Math.round(months);
        }
        if (format == "y") {
            return Math.round(years);
        }
    }
    

    It is not fully accurate, but very close. I ended up adding some addons to it to calculate in day week month year or hour, anyone can freely copy and use this code.

  • Axel Latvala
    Axel Latvala almost 13 years
    I guess I should replace the / with . when I want it to be in one of these formats: dd.mm.YYYY d.mm.YYYY dd.m.YYYY d.m.YYYY
  • shabunc
    shabunc almost 13 years
    @RobG, be carefull, I don't know what is finnish date format, but in javascript dates like this are parsed month/day/year, not day/month/year. I've always called it usa date format ;)
  • shabunc
    shabunc almost 13 years
    @Akke, there is no place to guess here, just try it yourself. You'll get the an invalid date.
  • Axel Latvala
    Axel Latvala almost 13 years
    Oh and could you clarify what s[2], --s[1], s[0] stands for?
  • RobG
    RobG almost 13 years
    @shabunc - there is no parsing, the date is split into its parts and passed to the Date constructor as individual components. Annoyingly, for the date 3 August, 2011 you can use the US format new Date('8/3/2011') or ISO and occasional European format new Date('2011/8/3') but not the most common format used world wide, i.e. '3/8/2011'
  • shabunc
    shabunc almost 13 years
    @RobG, oh, I see what you mean. Yep, I've been confused, sorry (