How to use datenum with a date represented as a scaler?
Show older comments
I have data I need to ingest that is date specific however, the data is represented as a scaler e.g. 20180924 with no spaces or hyphens. How do I get datenum to take this date in and separate it out into a vector so I can use it?
3 Comments
Walter Roberson
on 24 Sep 2018
Is the date numeric or character vector?
Are you using R2013a or earlier, or do you have an imposed requirement to use datenum? This is easier with datetime
Eric Metzger
on 24 Sep 2018
Stephen23
on 24 Sep 2018
@Eric Metzger: do you need to convert one such integer, or multiple integers?
Accepted Answer
More Answers (3)
ANKUR KUMAR
on 24 Sep 2018
If A is numeric, then
A=20180924
a1=num2str(A)
datenum(str2double({a1(1:4),a1(5:6),a1(7:8)}));
If you wish to store date in vector, then
A1=[str2double({a1(1:4),a1(5:6),a1(7:8)})]
6 Comments
Eric Metzger
on 24 Sep 2018
Walter Roberson
on 24 Sep 2018
If you want to break it up into numeric parts there are direct numeric ways such as mod()
ANKUR KUMAR
on 24 Sep 2018
A=20180924
a1=num2str(A)
datenum(str2double({a1(1:4),a1(5:6),a1(7:8)}));
A1=[({a1(1:4),a1(5:6),a1(7:8)})]
A =
20180924
a1 =
20180924
A1 =
1×3 cell array
'2018' '09' '24'
ANKUR KUMAR
on 24 Sep 2018
"I want to store it as a vector [2018 09 24]"
You can never store 09 as a matrix element because it reads as 09 as 9. But if you want to store as 09, then you must to move to class char.
Stephen23
on 24 Sep 2018
Note that the square brackets around str2double are totally superfluous:
Eric Metzger
on 24 Sep 2018
Walter Roberson
on 24 Sep 2018
1 vote
datetime(TheScalar, 'ConvertFrom', 'yyyymmdd')
You can convert the result to datenum if you insist: just double() the datetime
3 Comments
Walter Roberson
on 24 Sep 2018
Year=floor(TheScalar /10000);
Day=mod(TheScalar, 100);
Month=mod((TheScalar - Day) / 100, 100);
Steven Lord
on 24 Sep 2018
I would use the ymd function or the datevec function on the datetime object.
theScalar = 20180924
dt = datetime(theScalar, 'ConvertFrom', 'yyyymmdd')
[y, m, d] = ymd(dt)
DV = datevec(dt)
You can even go from the date vector back to a datetime.
dt2 = datetime(DV)
isequal(dt, dt2)
Walter Roberson
on 24 Sep 2018
It isn't clear what result is being looked for. If it is separated parts, with the implementation of sprintf -> str2num -> datenum -> datevec being considered, then my numeric code computes the pieces directly without needing any calls more expensive then mod.
Peter Perkins
on 1 Oct 2018
0 votes
If possible, use datetime rather than datenum/datestr/datevec. As Walter showed, you can convert directly from numeric to datetime. It's also possible that you do not need to store the separate pieces, since datetime lets you get at them any time you want, as a property.
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!