Convert mm/dd/yyyy to a form usable for datenum MATLAB

本小妞迷上赌 提交于 2019-12-11 22:11:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!