Comparing two dates with javascript or datejs (date difference)

Axel Latvala picture Axel Latvala · Aug 3, 2011 · Viewed 9.9k times · Source

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.

Answer

geoffrey.mcgill picture geoffrey.mcgill · Sep 21, 2011

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.