Using datenum on a cell array with different date formats
3 views (last 30 days)
Show older comments
I have a cell array with dates stored with two different formats, and want to convert this array to a column vector containing the numerical date value.
myDates = {'31.12.2009 23:58:31'; '25.12.2009'; '15.12.2009 15:18:10'};
This should return the following values: 7.341389989699074e+005, 734132, 7.341226376157408e+005
The two different formats are 'dd.mm.yyyy HH:MM:SS' and 'dd.mm.yyyy'. Calling datenum and specifying the wrong format causes an exception. Now, let's say myDates is really long. I could use a for loop with try/catch to go through myDates and try first with the long date format and then try with the shorter, but this takes a lot of time compared to just use datenum on the entire array at once. Is there a way I can tell datenum to try another format if the first one fails, or maybe go through the array in some efficient way and make all the dates the same format? Thank you in advance.
0 Comments
Accepted Answer
José-Luis
on 19 Nov 2012
Edited: José-Luis
on 19 Nov 2012
myDates = {'31.12.2009 23:58:31'; '25.12.2009'; '15.12.2009 15:18:10'};
idx = cellfun(@(x) isempty(regexp(x,':')),myDates);
myDates(idx) = cellfun(@(x) {[x ' 00:00:00']},myDates(idx));
your_vals = cellfun(@(x) datenum(x,'dd.mm.yyyy HH:MM:SS'),myDates);
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!