How to convert a string into a date or datenum?

I have a column, about [4000 x 1] with the format 'yyyymmddHH'. Yes, all the numbers are together.
And i need to get a date, or a datenum from that, but i cant, since functions like datetime need the numbers separated.
Anyone know how to get arround this?
Thank you.

Answers (1)

"... but i cant, since functions like datetime need the numbers separated."
I don't see that restriction mentioned anywhere in the DATETIME documentation.
S = ["2021061701";"2021010100";"1913061423"]
S = 3×1 string array
"2021061701" "2021010100" "1913061423"
D = datetime(S, 'InputFormat','yyyyMMddHH')
D = 3×1 datetime array
17-Jun-2021 01:00:00 01-Jan-2021 00:00:00 14-Jun-1913 23:00:00

6 Comments

Mine gives me error.
"Error using datetime (line 597)
Numeric input data must be a matrix with three or six columns, or else three, six, or seven separate numeric
arrays. You can also create datetimes from a single numeric array using the 'ConvertFrom' parameter."
If the data are stored as numeric where the digits of one value represent date units (ugh, ugh, ugh, a true abomination and crime against nature) then you can convert to string first:
VeryBadlyStoredDates = [2021061701;2021010100;1913061423] % should be illegal
VeryBadlyStoredDates = 3×1
2021061701 2021010100 1913061423
DT = datetime(string(VeryBadlyStoredDates), 'InputFormat','yyyyMMddHH')
DT = 3×1 datetime array
17-Jun-2021 01:00:00 01-Jan-2021 00:00:00 14-Jun-1913 23:00:00
Even better: create or import that data properly as datetime, rather than as numeric.
If you have to operate on the numbers, datetime can handle most of the conversion. You just have to handle the hour data.
VeryBadlyStoredDates = [2021061701;2021010100;1913061423]; % should be illegal
hourData = mod(VeryBadlyStoredDates, 100)
hourData = 3×1
1 0 23
yyyyMMdd = (VeryBadlyStoredDates-hourData)./100
yyyyMMdd = 3×1
20210617 20210101 19130614
DT = datetime(yyyyMMdd, 'ConvertFrom', 'yyyymmdd') + hours(hourData)
DT = 3×1 datetime array
17-Jun-2021 01:00:00 01-Jan-2021 00:00:00 14-Jun-1913 23:00:00
Converting it into a string worked!!
Thank you so much. And i totally agree, storing dates like this just gave me more work for nothing...
If you can, answer again in a seperate answer so i can accept your answer
@Bruno Carvalho: you can accept this answer, if one of the comments includes the solution.

Sign in to comment.

Categories

Asked:

on 17 Jun 2021

Commented:

on 18 Jun 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!