0
votes

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
have you tried: datenum(DateString, 'mm/dd/yyyy') - Amro
Oh, that works. Thanks. I was pretty sure I tried setting formatIn to 'mm/dd/yyyy' and it didn't work, but guess I did something wrong when trying that. - SugaKookie

1 Answers

2
votes

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