Is there a way to find the number of days between 2 LocalDate or DateTime values?
i.e. Given 2 dates I want to know the number of days between them taking the number of days in specific months and wether or not it’s a leap year into consideration?
It depends for what you want to use the counting of the days.
e.g. for Finance - interest rate calculations there are different day count conventions 30/360, act/act…
30/360:
function countDays30360(referenceDate: LocalDate) returns Number -> {
return (referenceDate.year() * 360 + referenceDate.month() * 30 + referenceDate.day());
};
function calcDiffDays30360(startDate: LocalDate, endDate: LocalDate) returns Number -> {
return (countDays30360(endDate) - countDays30360(startDate)) / 360;
};
If you want to calculate the actual number of days difference of the calendar days (act/act) I’m not aware of shortcuts in NPL. So this would need to calculate difference in years and months and figuring out the remaining days of the month of the start date.
For the leap year of the Gregorian calendar you could use the algo:
“Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but these centurial years are leap years if they are exactly divisible by 400. For example, the years 1700, 1800, and 1900 are not leap years, but the years 1600 and 2000 are.”
Here is a first try (but untested - so be careful):
// determines for the gregorian calendar if the year is a leap year
function isLeapYear(year: Number) returns Boolean -> {
if (year % 4 == 0) {
if ((year % 100 == 0) && (year % 400 != 0)) {
return false;
} else {
return true;
};
} else {
return false;
};
};
I was wondering, it would be helpful, if we would collect common functions per topic/industry and make these “available” to all of NPL users. Then all projects could leverage from it (something like a additional “NPL library”), not sure if this feasible and what’s the best approach to do this.
e.g. day count convention is e,g. used in Finance for cash flow calculations
There doesn’t seem to be any way to extract a Number of days from Period. From Duration, however, you can extract the Number of seconds, which you can use in a roundabout way:
@test
function test_number_of_days_between_dates(test: Test) -> {
var date1 = dateTimeOf(
year = 2016,
month = 2,
day = 1,
hour = 15,
minute = 15,
zoneId = valueOfZoneId(ZoneId.EUROPE_ZURICH)
);
var date2 = dateTimeOf(
year = 2016,
month = 3,
day = 1,
hour = 15,
minute = 15,
zoneId = valueOfZoneId(ZoneId.EUROPE_ZURICH)
);
var duration = date1.durationUntil(date2);
var days = duration.toSeconds() / 86400;
test.assertEquals(29, days);
};
I imagine we could consider adding methods for counting time units in Period, as well as more than just seconds for Duration.
I imagine it would work like the underlying java.time.Period, where Period.ofMonths(7).days == 0. But yes, that certainly wouldn’t address the use-case presented here.