简体   繁体   中英

To know if a date is superior at today - 24 hours

I have this array :

 ["AM", "2015", "01", "11"]

I use this code to create a new date :

var mois = (date1[2]-1);
var d1 = new Date(date1[1],mois,date1[3]);

I would like to know how can I compare my date (d1) with today - 24 hours ?

Edit on base of zoosuck reply :

I have now this code :

var jour_de_conge = new Date(date1[1],mois,date1[3]).getTime();
var jour_de_conge2 = new Date('2015','01','11').getTime(); 

The obtained timestamps are differents, but dates are the same (2015,01,11)

I don't understand...

You can use the getTime() method of a Date Object like this:

var today = new Date('2015','01','04').getTime(); // 1422979200000
var today_23 = new Date('2015','01','04','23').getTime(); // 1423062000000
var diff = today_23 - today;
if (diff <= 86400000) {
  alert('same day');
} else {
  alert('other day');
}

there are 86400000 milliseconds in one day. Or you can use the seconds to judge which is the same.

Try it:

var dateUnits = {
    miliseconds: 0,
    seconds: 1,
    minutes: 2,
    hours: 3,
    days: 4,
    month: 5,
    years: 6
};


function dateDiff(date1,date2,unitRetur) {
    var unit = des.dateUnits.miliseconds;
    if (arguments.length < 2) {
        return null;
    }
    if (arguments.length = 3) {
        unit = arguments[2];
    }


    var dif = date2 - date1;


    switch (unit){

        case des.dateUnits.seconds:
            //86400000
            dif = Math.round(dif/1000);
            break;
        case des.dateUnits.minutes:

            dif = Math.round(((dif / 1000)/60));
            break;
        case des.dateUnits.hours:
            dif = Math.round((((dif / 1000) / 60) / 60));
            break;
        case des.dateUnits.days:

            dif = Math.round((((dif / 1000) / 60) / 60)/24);
            break;

        case des.dateUnits.month:

            dif = Math.round((((((dif / 1000) / 60) / 60) / 24)) / 30);
            break;

        case des.dateUnits.years:

            dif = Math.round((((((dif / 1000) / 60) / 60) / 24))/360);
            break;


    }

    return dif;


}

var mois = (date1[2] - 1);
var d1 = new Date(date1[1], mois, date1[3]);

var dif = dateDiff(d1, new Date(), dateUnits.hours);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM