问题
I want to convert a column of dates from a cell from the format mm/dd/yyyy (They come in the form 4/10/2007, or with double digit months, 10/10/2007) to yyyy-mm-dd, and plot it. So I need to turn mm/dd/yyyy into serial date number.
When the date column is already in the form yyyy-mm-dd, the following code works:
DateString = PM25data(:,11); % Pull out dates
formatIn = 'yyyy-mm-dd';
x1 = datenum(DateString,formatIn); % Convert to datnum
However, since the date form here is mm/dd/yyyy (for example, 4/12/2007), I can't get the above format to work with the error
DATENUM failed.
Caused by:
Error using dtstr2dtnummx
Failed on converting date string to
date number.
I also tried this code:
DateString = PM25data(2:end,1);
formatOut = 'yyyy-mm-dd';
x4 = datenum(DateString, formatOut); % Convert to datnum
But it runs this error:
Cannot convert input into specified date
string.
DATENUM failed.
How can I get datenum to work in this case?
回答1:
Format 'mm/dd/yyyy'
is just format 23 in datenum
. So:
>> string = '4/12/2007';
>> datenum(string,23)
ans =
733144
Or define format explicitly:
>> string = '4/12/2007';
>> datenum(string,'mm/dd/yyyy')
ans =
733144
来源:https://stackoverflow.com/questions/21126185/convert-mm-dd-yyyy-to-a-form-usable-for-datenum-matlab