简体   繁体   中英

How to get the duration of days from today to a specified date in javascript?

假设指定的日期为2010-11-9 ,如何以编程方式获取持续时间?

What about this from here ?

function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}
Math.abs(new Date() - Date.parse("Nov 9, 2010")) / ( 60*60*24) / 1000

收益:

24.786491909722223

It's not exactly appropriate, but you can call getTime() from a Date instance to get the number of milliseconds since the epoch. Subtract two of those and divide by the number of milliseconds in a day.

If you want, you can take the dates back to the start of their days by explicitly setting the hours, minutes, and seconds to zero:

function startOfDay(d) {
  d.setHours(0); d.setMinutes(0); d.setSeconds(0); d.setMilliseconds(0);
  return d;
}

var startOfToday = startOfDay(new Date());
function daysTo(from, to){
    // to and from may be
    // strings in the form'yyyy-mm-dd' or 'yyyy-m-d'
    // split the strings on dashes and possible leading 0, 
    // to avoid '08' becoming octal '10'

    to= to.split(/\-0?/);
    to= new Date(+to[0], to[1]-1, +to[2]);

    from= from.split(/\-0?/);
    from= new Date(+from[0], from[1]-1, +from[2]);

    return Math.round((to-from)/86400000));
}

daysTo('2010-9-10','2011-9-10') // or daysTo('2010-09-10','2011-09-10')

/* returned value: (Number) 365 */

Rounding the result smooths out daylight savings offsets.

If you create a new date without specifying time, the date will be set at midnight local time.

Subtracting date objects converts them to milliseconds- you don't need to use getTime().

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