Can't calculate difference between two dates in years, months, days. The problem is every month have 30 days, and every year have 365 days with no exceptions. There are a lot of topics here, but i haven't found any which can solve my problem or help with it. Every topic I found just solve problem calculating difference in normal way, which is simple. How can I calculate such difference?
I'm using Java 7 (there is no opportunity to install joda time) and groovy 2.4.0.
Examples are:
date from date to y m d
2014-02-01 - 2015-02-01 => 1 0 1
2000-02-10 - 2003-01-18 => 2 11 9
2004-02-02 - 2004-06-24 => 0 4 23
Thanks.
Came up with this in Groovy, not sure if it fits your requirements, but it gives the results in the question:
def dateMalarkey(Date from, Date to) {
def val = [from, to].collect { d ->
def cal = Calendar.instance
cal.time = d
[y: cal[Calendar.YEAR], m: cal[Calendar.MONTH], d: cal[Calendar.DAY_OF_MONTH]]
}.inject { p, n ->
[y: Math.abs(p.y - n.y), m: Math.abs(p.m - n.m), d: Math.abs(p.d - n.d) + 1]
}
val.days = val.y * 365 + val.m * 30 + val.d
val
}
def inputs = [
[from: '2014-02-01', to: '2015-02-01'],
[from: '2000-02-10', to: '2003-01-18'],
[from: '2004-02-02', to: '2004-06-24']
]
inputs.each { d ->
println "$d.from - $d.to => " +
dateMalarkey(Date.parse('yyyy-MM-dd', d.from), Date.parse('yyyy-MM-dd', d.to))
}