BAD_SEED
BAD_SEED

Reputation: 5056

From UTC to date vector

I have a set of date expressed in form of 2010-07-31T23:01:57Z. I need to transform it into vector. I could do this as datavec(mydate) it will transform automatically the string into vector, but this function doesn't accept UTC string date. So I have rudely resolved in this way:

a = `2010-07-31T23:01:57Z`; %UTC date format
a(20) = '';                 %remove Z
a(11) = ' ';                %replace T with a space 
a = datavec(a);             % [2010, 7, 31, 23, 1, 57]

In this way a is a datevector and I can use etime(T1, T0) to compute time difference between T1 and T0. Is this the unique way or I can do something stylish?

Upvotes: 1

Views: 1676

Answers (3)

Amro
Amro

Reputation: 124563

As stated by others, you could specify the format of the expected date strings to functions like DATEVEC and DATENUM. Example:

%# set of dates and an initial date
T0 = '2010-01-01T00:00:00Z';
T = repmat({'2010-07-31T23:01:57Z'}, [10 1]);   %# cell array

%# format of datetime
frmt = 'yyyy-mm-ddTHH:MM:SS';

%# convert to serial date numbers, and compute difference between all T and T0
n = datenum(T,frmt);
n0 = datenum(T0,frmt);
tdiff = bsxfun(@minus, n, n0);

Alternatively, if you have an unusual date format, you can always split and parse it yourself with functions like TEXTSCAN:

vec = zeros(numel(T),6);
for i=1:numel(T)
    C = textscan(T{i}, '%f', 'Delimiter',['-' ':' 'T' 'Z']);
    vec(i,:) = C{1};
end
n = datenum(vec);

Note that in both cases, you can convert back serial times to date strings with the DATESTR function.

Upvotes: 1

Doresoom
Doresoom

Reputation: 7458

As Marc suggests, all you have to do is 'help' MATLAB a bit by specifying the data format.

datevec('2010-07-31T23:01:57Z','yyyy-mm-ddTHH:MM:SS')

should do the trick.

Upvotes: 1

Marc
Marc

Reputation: 3323

use the fieldSpecIn part of the datevec() call. Read all about it here: http://www.mathworks.com/help/techdoc/matlab_prog/bspgcx2-1.html#bspgc4m-1

Except for the TZ spec at the end of your string and the -'s and :'s, yours is identical to the standard ISO 8601 format. You can either modify yours, or create your own spec string.

Please note that Matlab time has no concept of time zone. You must keep track of that yourself.

Upvotes: 1

Related Questions