Reputation: 529
I have a string in Matlab that represents the date, for instance today would be 20140703
. What I need to do it perform simple calculations (additions and subtractions) on the date, the most used function would be to subtract one week, hence making the result 20140626
.
In the scenario the date is 20140710
it would be easy to subtract 7 and have the result (20140703
), but if the date crosses into a new month then problems start to arise because of different days in the months etc!
How can this be solved??
Upvotes: 2
Views: 67
Reputation: 1426
The standard way to go about this is to use unix_time [1] or if you're going to stay exclusively in MATLAB, its own "MATLAB time".
For this purpose there are functions that help you parse strings of varying format and convert them to "MATLAB time". [2]
Matlab time is simply a double precision float that indicates days since Jan 1. 0000 (precision is better than days due to decimal points). You can perform normal arithmetic operations on Matlab time and then convert back to the format you want.
Edit: Note that if performance is a concern, you are going to run into trouble with these functions because they perform a lot of checks to be able to cope with a wide variety of input formats. For certain functions you can get some C sources through the file exchange that, when compiled to mex, will perform much better. [3]
[1] http://en.wikipedia.org/wiki/Unix_time
[2] see documentation for datenum
and datestr
[3] http://www.mathworks.com/matlabcentral/fileexchange/28093-datestr2num
Upvotes: 1
Reputation: 114876
Use datestr
and datenum
with the format string 'yyyymmdd'
to convert a digits (input as string) and convert them to a serial number representing days.
>> DateNumber = datestr( datenum('20140703','yyyymmdd') - 7, 'yyyymmdd')
DateNumber =
20140626
if your input date 20140703
is a number and not a string, you can easily convert it into a string using num2str
.
Upvotes: 3