how to write a function that calulates the days until next birthday from now in matlab

main.m
function days_until_birthday = calc_days_until_birthday(year, month, day)
% This function takes a person's birthday in year-month-day format and
% calculates the number of days until their next birthday from the current
% date.
%
% Example usage:
% >> today = datetime('now');
% >> days_until_birthday = calc_days_until_birthday(1990, 3, 12)
% 
% days_until_birthday =
%
%     276
%
% >> next_birthday = today + days_until_birthday;
% >> disp(['Your next birthday is on ' datestr(next_birthday, 'dddd, mmmm dd, yyyy')])

this_year_birthday = datetime(year, month, day);
this_year_birthday.Year = year;
next_birthday = this_year_birthday;
if next_birthday < datetime('now')
    next_birthday.Year = next_birthday.Year + 1;
end
days_until_birthday = days(next_birthday - datetime('now'));
end
791 chars
25 lines

The idea of the function is to calculate the next birthday from "now" and return the number of days difference between "now" and that date. If the calculated birthday is already past in the current year, we add one year to the birthday to get the next one. We use the days function to calculate the difference in days between two datetime objects.

To use the function, just call it with the person's birthday in year-month-day format (as separate arguments, not as a single string). Here's an example usage:

main.m
>> today = datetime('now')
today =
   14-Dec-2021 11:16:53
>> calc_days_until_birthday(1990, 3, 12)
ans =
   77
112 chars
7 lines

This means that if the person with birthday March 12, 1990 were still alive, their next birthday would be in 77 days from today.

gistlibby LogSnag