How can I convert a cell array of "random dates in the year" into time in year?

2 views (last 30 days)
For ex: My input vector has random dates like 1993-4-1,1993-4-28 etc.Output should be 1993.000,1993.0039,1993.0078.I have used different functions (datevector, datenum etc). But they convert the date either to date numbers (730990) or yr month day format; not in the above output form. Btw I have to extract the input array from a .mat file. Thanks...

Accepted Answer

Star Strider
Star Strider on 4 Oct 2015
One possibility:
datestrs = {'1993-4-1'; '1993-4-28'}; % Date String Cell Array
dnvct = datenum(datestrs, 'yyyy-mm-dd'); % Convert To Date Numbers
dateyr = str2num(datestrs{1}(1:4)); % Get Year (Numeric)
range_yr_dn = datenum([dateyr 1 1 0 0 0; dateyr 12 31 23 59 59]); % Start, End Of Year
range_yr_dn_diff = diff(range_yr_dn); % Year Range
year_fraction = (dnvct - range_yr_dn(1))./range_yr_dn_diff; % Year Fraction For Each Input Date
Result = [repmat(dateyr, size(year_fraction,1), 1) + year_fraction] % Year Fraction In Desired Format
Result =
1993.2
1993.3

More Answers (2)

Matt J
Matt J on 4 Oct 2015
Edited: Matt J on 4 Oct 2015
Here's a way using datetime,
>> yourDates=datetime({ '1993-4-1','1993-4-28'},'InputFormat','yyyy-M-d')
yourDates =
01-Apr-1993 28-Apr-1993
>> doy=day(yourDates,'dayofyear');
>> [Y,M,D]=ymd(yourDates); M(:)=12; D(:)=31;
>> doyDec31=day(datetime(Y,M,D),'dayofyear');
>> result=Y+doy/doyDec31;

Stephen23
Stephen23 on 4 Oct 2015
Edited: Stephen23 on 5 Oct 2015
One easy way would be to use my FEX submission num2date8601, which returns date strings whose format are controlled by tokens. One option is to provide a decimal fraction of any date/time unit. Here is an example with four decimal places of the calendar year:
>> C = {'1993-4-1'; '1993-4-28'};
>> arrayfun(@(n)str2double(datestr8601(n,'y4')),datenum(C))
ans =
1993.2465
1993.3205

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!