I am using Velocity and want to get an accurate date diff in full years between two dates. if you use this tool you will see that there has been 64 full years between these two dates. All I can get velocity to return is 65 years
I have tried the following code:
($date is dateTool, $compareDate is ComparisonDateTool and $number is NumberTool)
#set( $defaultTimeZone = $date.getTimeZone().getTimeZone("GMT") )
#set( $defaultLocale = $date.getLocale() )
#set( $ISO8601 = "yyyy-MM-dd'T'HH:mm:ss" )
#set ($resDateObj = $date.toDate($ISO8601,"1954-06-26T00:00:00",$defaultLocale,$defaultTimeZone))
#set ($incepDateObj = $date.toDate($ISO8601,"2019-06-20T00:00:00",$defaultLocale,$defaultTimeZone))
#set($diffRemaining = $compareDate.difference($resDateObj, $incepDateObj).getYears())
#set($weeksRemaining = $number.toNumber($diffRemaining).intValue())
years is: $weeksRemaining
Output of this code is: years is: 65
I imagine that this is down to leap years as the total number of common years (365 days) is 6502.74.
In reality 64 years, 11 months, 25 days have passed. Any ideas on how to get Velocity to return 64 for this calculation.
The implementation of the ComparisonDateTool is quite broken since it just calculates the number of milliseconds between the dates, then approximate years, months and days by dividing by constants.
You can break down the calculation in years, months and days using the Calendar object:
#set( $defaultTimeZone = $date.getTimeZone().getTimeZone("GMT") )
#set( $defaultLocale = $date.getLocale() )
#set( $ISO8601 = "yyyy-MM-dd'T'HH:mm:ss" )
#set ($resDateObj = $date.toDate($ISO8601,"1954-06-26T00:00:00"))
#set ($incepDateObj = $date.toDate($ISO8601,"2019-06-20T00:00:00"))
#set ($resCalObj = $date.toCalendar($resDateObj))
#set ($incepCalObj = $date.toCalendar($incepDateObj))
## years
#set($years = $incepCalObj.get(1) - $resCalObj.get(1))
## months
#set($months = $incepCalObj.get(2) - $resCalObj.get(2))
#if($months < 0)
#set($years = $years - 1)
#set($months = $months + 12)
#end
## days
#set($days = $incepCalObj.get(5) - $resCalObj.get(5))
#if($days < 0)
#set($months = $months - 1)
#if($months < 0)
#set($years = $years - 1)
#set($months = $months + 12)
#end
## go to previous month
$incepCalObj.add(2, -1)
#set($days = $days + $incepCalObj.getActualMaximum(5))
#end
years: $years
months: $months
days: $days
wich gives the result:
years: 64
months: 11
days: 25
You should note that this code doesn't really belong in a template. This calculation should be made on the java side, in a tool of your own.
(edited to fix the number of days, which can properly be defined) (edited to fix the month variable name)