views:

40

answers:

4

Suppose the specified date is 2010-11-9, how to get the duration programatically?

A: 

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());
Pointy
Yes but you may have a difference of 1 day with the real difference...
romaintaz
No,I don't want to care of hours,only days.
ollydbg
Well then chop off the fractional part of the result.
Pointy
How are you going to get the difference with `2010-11-9` by `startOfToday` ?
ollydbg
Well you have to construct a `Date` instance for it. `new Date(2010, 10, 9)` would do it. (Note that months are counted 0 .. 11 for Javascript `Date` objects.)
Pointy
A: 
Math.abs(new Date() - Date.parse("Nov 9, 2010")) / ( 60*60*24) / 1000

returns:

24.786491909722223
動靜能量
+1  A: 

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)

}
Galwegian
But my `date2` is actually a string like `2010-11-9`..
ollydbg
A: 
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().

kennebec