Reputation: 339
I need to count X days starting on some specific day, but I don't know how to sum these days accosrding to the number of days on each month (e.g. February having 28 or 29, March 31 but April 30...).
I know there is the function daysact( startDate, endDate )
, but this way I have to try dates until I reach the result I want, and what I need is for the program to count X days from the startDate
and return the endDate
. For example, if I want to count 90 days from tomorrow, I have done:
startDate = '8-jan-2016';
endDate = '7-apr-2016';
numDays = daysact( startDate, endDate );
but I have had to try dates until the function returned exactly 90 (I know it's fairly simple, but the final program will have to do this for different values of days and different starting dates...)
Upvotes: 2
Views: 705
Reputation: 18177
startDate = '8-jan-2016';
NumDays = 90;
tmp = datevec(startDate);
tmp(3)=tmp(3)+90;
endDate = datestr(tmp)
This uses datevec
to transform your string into a vector of [Y M D HH MM SS]
, so by adding the desired number of days, 90, to the third element you add 90 days to the start date. Then transform the vector back using datestr
, which makes it a recognisable date again.
As per @excaza's comment datenum
does approximately the same thing, returning the number of days since 0 January 0000
, so the same could be accomplished using:
startDate = '8-jan-2016';
NumDays = 90;
endDate = datestr(datenum(startDate)+NumDays);
which is a bit more concise, at the cost of having to convert everything to fractions of days.
One-lining it because why not:
endDate = datestr(datenum('8-jan-2016')+90);
Upvotes: 3
Reputation: 23
2014b and later:
datetime(2016,1,8) + days(90)
datetime(2016,1,8) + 90
datetime('today') + days(90)
datetime('today') + 90
datetime('tomorrow') + days(90)
datetime('tomorrow') + 90
Upvotes: 3
Reputation: 2802
I wanted to post this as an alternative. It was mentioned by @excaza in a comment to @Adriaan's answer.
myDate = datenum(2016,1,8); % datenumber for january 8 2016
newDate = myDate + 90; % add 90 days
newDate2 = myDate + 2/24; % add 2 hours
newDate3 = myDate + 93/1440; % add 93 minutes
Then you can print the dates with datestr
.
datestr(newDate)
ans =
07-Apr-2016
>> datestr(newDate2)
ans =
08-Jan-2016 02:00:00
>> datestr(newDate3)
ans =
08-Jan-2016 01:33:00
datenum
can take many inputs and even user defined formats to read the date strings.
Upvotes: 1