This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
sample_code:datediff [2016/07/23 08:15] stevegarman created |
sample_code:datediff [2016/07/29 13:39] (current) |
||
---|---|---|---|
Line 10: | Line 10: | ||
* Calculating the difference between two dates in years, months and days. | * Calculating the difference between two dates in years, months and days. | ||
- | ==== What if I don't have the plugin? ==== | + | ===== What if I don't have the plugin? |
Of course you could always buy it or take out a Premium subscription. | Of course you could always buy it or take out a Premium subscription. | ||
Line 27: | Line 27: | ||
// the dateDiff function does not rely on the plugin | // the dateDiff function does not rely on the plugin | ||
- | |||
app.LoadPlugin( " | app.LoadPlugin( " | ||
var date1, | var date1, | ||
Line 155: | Line 154: | ||
ret.sign = " | ret.sign = " | ||
} | } | ||
+ | |||
// populate variables for comparison | // populate variables for comparison | ||
var year1 = dt1.getFullYear(); | var year1 = dt1.getFullYear(); | ||
Line 167: | Line 166: | ||
// calculate differences | // calculate differences | ||
- | ret['years' | + | ret.years = year2 - year1; |
- | ret['months' | + | ret.months = month2 - month1; |
- | ret['days' | + | ret.days = day2 - day1; |
+ | |||
// cope with any negative values. | // cope with any negative values. | ||
- | if (ret['days' | + | if (ret.days < 0) |
{ | { | ||
// can't span months by arithmetic, use temp date | // can't span months by arithmetic, use temp date | ||
var dtmp = new Date(dt1.getFullYear(), | var dtmp = new Date(dt1.getFullYear(), | ||
- | |||
var numDays = dtmp.getDate(); | var numDays = dtmp.getDate(); | ||
- | + | ||
- | ret['months' | + | ret.months -= 1; |
- | ret['days' | + | ret.days += numDays; |
} | } | ||
+ | |||
// months is pure arithmetic | // months is pure arithmetic | ||
- | if (ret['months' | + | if (ret.months < 0) |
{ | { | ||
- | ret['months' | + | ret.months += 12; |
- | ret['years' | + | ret.years -= 1; |
} | } | ||