How can I use DATENUM on a cell array of dates (specified without time information) with each date in a different format?
17 views (last 30 days)
Show older comments
MathWorks Support Team
on 27 Jun 2009
Edited: MathWorks Support Team
on 18 Nov 2022
When I declare a cell array of dates in different formats, I receive an error on using DATENUM. When the following code is typed:
date_array = {'02/06/2002 ', '2/5/2002 ', '2/4/2002 ', '1-Feb-02 ', '1/31/2002 ','1/30/2002 '};
date_num = datenum(date_array);
The following error is obtained:
ERROR: ??? Error using ==> datenum at 174 DATENUM failed. Error using ==> dtstr2dtvecmx Failed on converting date string to date number.
Accepted Answer
MathWorks Support Team
on 18 Oct 2013
The ability to use DATENUM on a cell array of dates having different formats is not available.
Ideally, all dates in a cell array of strings input to DATENUM should have the same format. If this is not possble,
as a workaround, consider using the CELLFUN function to operate DATENUM on each element of the cell array as given below.
For example,
date_array = {'02/06/2002', '2/5/2002', '2/4/2002', '1-Feb-02', '1/31/2002','1/30/2002'};
date_num = cellfun(@datenum, date_array);
1 Comment
Stephen23
on 24 Feb 2016
Edited: MathWorks Support Team
on 18 Nov 2022
Your problem is totally different to this question, as you have (apparently) exactly the same date format for each date. In any case the solution is easy by simply reading the datevec documentation:
>> C = {'4/1/2012' '4/2/2012' '4/3/2012' '4/4/2012' '4/5/2012' '4/6/2012' '4/7/2012' '4/8/2012' '4/9/2012' '4/10/2012' '4/11/2012' '4/12/2012' '4/13/2012' '4/14/2012' '4/15/2012' '4/16/2012' '4/17/2012' '4/18/2012' '4/19/2012' '4/20/2012' '4/21/2012' '4/22/2012' '4/23/2012' '4/24/2012' '4/25/2012' '4/26/2012' '4/27/2012' '4/28/2012' '4/29/2012' '4/30/2012' '5/1/2012'};
>> datevec(C,'mm/dd/yyyy')
ans =
2012 4 1 0 0 0
2012 4 2 0 0 0
2012 4 3 0 0 0
2012 4 4 0 0 0
2012 4 5 0 0 0
2012 4 6 0 0 0
...etc
2012 4 30 0 0 0
2012 5 1 0 0 0
More Answers (0)
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!