Comparing two dates with javascript or datejs (date difference)

夙愿已清 提交于 2019-12-21 08:00:10

问题


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.


回答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.




回答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.




回答3:


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. 


来源:https://stackoverflow.com/questions/6923393/comparing-two-dates-with-javascript-or-datejs-date-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!