Javascript DateDiff

后端 未结 4 1759
星月不相逢
星月不相逢 2021-01-12 04:15

I am having a problem with the DateDiff function. I am trying to figure out the Difference between two dates/times. I have read this posting (What's the best way to calc

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-12 04:38

    Okay for those who would like a working example here is a simple DateDiff ex that tells date diff by day in a negative value (date passed already) or positive (date is coming).

    EDIT: I updated this script so it will do the leg work for you and convert the results in to in this case a -10 which means the date has passed. Input your own dates for currDate and iniPastedDate and you should be good to go!!

    //Set the two dates
    var currentTime   = new Date()
    var currDate      = currentTime.getMonth() + 1 + "/" + currentTime.getDate() + "/" + currentTime.getFullYear() //Todays Date - implement your own date here.
    var iniPastedDate = "8/7/2012" //PassedDate - Implement your own date here.
    
    //currDate = 8/17/12 and iniPastedDate = 8/7/12
    
    function DateDiff(date1, date2) {
        var datediff = date1.getTime() - date2.getTime(); //store the getTime diff - or +
        return (datediff / (24*60*60*1000)); //Convert values to -/+ days and return value      
    }
    
    //Write out the returning value should be using this example equal -10 which means 
    //it has passed by ten days. If its positive the date is coming +10.    
    document.write (DateDiff(new Date(iniPastedDate),new Date(currDate))); //Print the results...
    

提交回复
热议问题