I have
month(Date);
this will give me the number 1,2,3,...
But I want to have 01,02,03,.. as months. Please advise.

댓글 수: 3

dpb
dpb 2020년 7월 2일
Output formatting is independent of value...need to know where you want this appearance to be.
If it's the Date itself, then set the .Format property.
Eventually want to create yyyy-mm variable
yyyy_mm=strcat(num2str(year),'-',num2str(month));
and I want to have "month' as a two digit number so that output is like '2020-01'.
dpb
dpb 2020년 7월 3일
편집: dpb 2020년 7월 3일
Hadn't seen this comment ere now--
Again, use the proper variable class for the purpose --
>> Date = datetime('now') % build the date variable -- how is up to your application
Date =
datetime
03-Jul-2020 12:39:53
>> Date.Format='yyyy-MM' % set the desired display format--anything that uses will be as shown on output
Date =
datetime
2020-07
>> string(Date) % if you really must have a string or cellstr(), it's what you get automagically
ans =
"2020-07"
>> disp(Date) % or just use the variable; its output format is as requested
2020-07
>>
As another poster noted, do NOT use month as a variable; that aliases the builtin month() function.

댓글을 달려면 로그인하십시오.

답변 (2개)

Star Strider
Star Strider 2020년 7월 2일

3 개 추천

To have leading zeros, it has to be a character array or string variable.
Try this:
Date = datetime('now');
mth = sprintf('%02d',month(Date));
producing:
mth =
'07'
.

댓글 수: 3

Or...
Date.Format='MM';
which produces
>> disp(Date)
07
>>
madhan ravi
madhan ravi 2020년 7월 2일
편집: madhan ravi 2020년 7월 2일
Date = datetime('now',"Format",'MM') % which is what i mean't in my comment ;)
I also didn’t see this Comment until now.
Expanding on my initial Answer:
Date = datetime('now')+calmonths(0:3).';
Date.Format = 'yyyy-MM';
Out = Date
produces:
Out =
4×1 datetime array
2020-07
2020-08
2020-09
2020-10
.

댓글을 달려면 로그인하십시오.

madhan ravi
madhan ravi 2020년 7월 2일
편집: madhan ravi 2020년 7월 3일

0 개 추천

ix = m < 10 % m is the output of the month(...) , by the way it can be set by Format in datetime(...)
M = "" + m
M(ix) = 0 + "" + m(ix)

댓글 수: 4

alpedhuez
alpedhuez 2020년 7월 3일
편집: alpedhuez 2020년 7월 3일
So suppose I have a 'month' variable. How will it work?
dpb
dpb 2020년 7월 3일
How will it work for what?
As said before, w/o any context we have no klew what you're trying to accomplish.
The display format is independent of the data; is it the output you're concerned about how it looks or something else?
madhan ravi
madhan ravi 2020년 7월 3일
편집: madhan ravi 2020년 7월 3일
yyyy_mm = datetime("now","Format","uuuu-MM")
m = randi([1, 12], 10, 1); % months example
ix = m < 10 ;
M = "" + m;
M(ix) = 0 + "" + m(ix)
Note: Naming a variable month is a terrible idea!!!
alpedhuez
alpedhuez 2020년 7월 3일
Let me work on it.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

질문:

2020년 7월 2일

댓글:

2020년 7월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by