开发者

Comparing two dates with javascript or datejs (date difference)

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) {
    开发者_JAVA技巧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.


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.


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.


Using the Date object:

var today = Date.today();
var dateToday = Date.parse(today.toString('MMMM d, yyyy'));

var prevMonthDate = dateToday.addDays(-30);

var difference = (dateToday - prevMonthDate)/86400000;

console.log(difference);   //will give you the difference in days. 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜