How do I convert this string to a date ?

43 views (last 30 days)
Jules PASCO on 26 May 2021
Commented: Jules PASCO on 2 Jun 2021
Hi everybody !
I'm trying to turn this string to a date (from a txt file): 2021-05-11T14:11:00Z to 'yyyy-MM-dd HH:mm:ss'.
I tried with datetime(ref_time(h, 1),'InputFormat', 'yyyy-MM-dd e HH:mm:ss e','Format','yyyy-MM-dd HH:mm:ss') with an 'e' replacing the 'T' and 'Z' but id doesn't work...

Answers (2)

Asmit Singh
Asmit Singh on 26 May 2021
Since you are trying to convert strings to date with literals like 'T' and 'Z', you may want to look at the "Date and Time from Text with Literal Characters" section in the documentation.
The below code converts the given string format to matlab datetime variable.
myDate = "2021-05-11T14:11:10Z"
Jules PASCO on 2 Jun 2021
Ok! It works now!
To make the dates match the values, I imported my data files as arrays instead of vectors/matrices like before, but I have the impression that matlab differentiates arrays from matrices, which prevents me from doing the date conversion...
If I can't do it any other way I'd switch my array to matrix but the point of array is that it recognizes dates.

Sign in to comment.

Allen on 26 May 2021
Try running a string replacement to remove "T" and "Z" from your string before reformatting to datetime.
str = "2021-05-11T14:11:00Z";
datetime(regexprep(str,["T","Z"],[" ",""]))
ans = datetime
11-May-2021 14:11:00
  1 Comment
Stephen23 on 26 May 2021
The "T" is specified in ISO 8601, it would be a very unfortunate if DATETIME could not handle it:
The "Z" refers to the Zulu time zone:
and as such it conveys important information which cannot be disregarded:
S = '2021-05-11T14:11:00Z';
T = datetime(S,'InputFormat','yyyy-MM-dd''T''HH:mm:ssZ', 'TimeZone','UTC')
T = datetime
11-May-2021 14:11:00
T.TimeZone = 'Asia/Shanghai'
T = datetime
11-May-2021 22:11:00

Sign in to comment.


Community Treasure Hunt

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

Start Hunting!

Translated by