//*** This code is copyright 2004 by Gavin Kistner, !@phrogz.net
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
//*** Reuse or modification is free provided you abide by the terms of that license.
//*** (Including the first two lines above in your source code satisfies the conditions.)
// Return a date as a duration (since Jan 1 1970)
// See example below for argument description.
Date.prototype.asDuration=function( opts ){
var decs=/dec(\d*)/i, zero=/evenifzero/i;
var f={}; f.s=1000; f.m=f.s*60; f.h=f.m*60; f.d=f.h*24; f.w=f.d*7; f.y=f.d*365.25;
var pieces = [
{ n:'ms',p:'ms', s:'ms', f:1 },
{ n:'s', p:'seconds', s:'second', f:f.s },
{ n:'m', p:'minutes', s:'minute', f:f.m },
{ n:'h', p:'hours', s:'hour', f:f.h },
{ n:'d', p:'days', s:'day', f:f.d },
{ n:'w', p:'weeks', s:'week', f:f.w },
{ n:'y', p:'years', s:'year', f:f.y }
];
var val = this.valueOf(),o='',opt,v,d,p;
if (opts) for (var i=pieces.length-1;i>=0&&!d;i--){
if (!(opt=opts[(p=pieces[i]).n])) continue;
d=decs.exec(opt);
if (val
"1 day, 4 minutes"
diff.asDuration( {d:1,h:'evenifzero',m:1} );
--> "1 day, 0 hours, 4 minutes"
To force a value to display with decimals, put 'dec' in the property value:
diff.asDuration( {d:1,h:'dec',m:1} );
--> "1 day, 0.06666666666666667 hours"
To force a specific number of decimals, append digits after 'dec':
diff.asDuration( {d:1,h:'dec1',m:1} );
--> "1 day, 0.1 hours"
diff.asDuration( {d:1,h:'dec2',m:1} );
--> "1 day, 0.07 hours"
If the smallest unit specified is set not to show decimals, but more than
half of that unit is left over, the value will be truncated. Set the last
item to 'dec0' to force it to round up if appropriate. For example:
var d1 = new Date('5/1/2004 12:00:00 pm');
var d2 = new Date('5/1/2004 1:10:59 pm');
var diff = new Date(d2-d1);
diff.asDuration( {d:1,h:1,m:1,s:1} );
--> "1 hour, 10 minutes, 59 seconds"
diff.asDuration( {d:1,h:1,m:1} );
--> "1 hour, 10 minutes"
diff.asDuration( {d:1,h:1,m:'dec0'} );
--> "1 hour, 11 minutes"
diff.asDuration( {m:'dec2'} );
--> "70.98 minutes"
*************************************************************************** */