MATLAB Answers

Convert Text into Date Format

16 views (last 30 days)
JBA Miller
JBA Miller on 1 Mar 2021
Commented: dpb on 1 Mar 2021
Hi, I struggle a lot!
I want to convert the text 196307 into a date format that MATLAB recognizes as "July 1963".
How can I do that?

Answers (3)

dpb
dpb on 1 Mar 2021
>> datetime('196307','InputFormat','yyyyMM')
ans =
datetime
01-Jul-1963
>>
or
>> datetime([floor(196307/100) 196307-floor(196307/100)*100 1])
ans =
datetime
01-Jul-1963
>>
Your choice depending upon whether you're starting with a string or a number.

Allen
Allen on 1 Mar 2021
Try the following:
% Code works with either a string or numerical input
str = '196307';
datestr(datenum(str,'yyyymm'),'mmmm yyyy')
num = 196307;
datestr(datenum(num,'yyyymm'),'mmmm yyyy')

Steven Lord
Steven Lord on 1 Mar 2021
If you have a number:
x = 196307;
datetime(100*x+1, 'ConvertFrom', 'yyyymmdd')
ans = datetime
01-Jul-1963
If you have text:
y = string(x);
datetime(y, 'InputFormat', 'yyyyMM')
ans = datetime
01-Jul-1963
  1 Comment
dpb
dpb on 1 Mar 2021
datetime(100*x+1, 'ConvertFrom', 'yyyymmdd')
Clever! +1

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!