Month as a two digit number
32 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
dpb
le 3 Juil 2020
Modifié(e) : dpb
le 3 Juil 2020
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.
Réponses (2)
Star Strider
le 2 Juil 2020
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 commentaires
madhan ravi
le 2 Juil 2020
Modifié(e) : madhan ravi
le 2 Juil 2020
Date = datetime('now',"Format",'MM') % which is what i mean't in my comment ;)
Star Strider
le 3 Juil 2020
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
le 2 Juil 2020
Modifié(e) : madhan ravi
le 3 Juil 2020
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 commentaires
madhan ravi
le 3 Juil 2020
Modifié(e) : madhan ravi
le 3 Juil 2020
Replying to your comment in https://in.mathworks.com/matlabcentral/answers/558439-month-as-a-two-digit-number#comment_923660:
yyyy_mm = datetime("now","Format","uuuu-MM")
Replying to your comment in https://in.mathworks.com/matlabcentral/answers/558439-month-as-a-two-digit-number#comment_923603
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!!!
Voir également
Catégories
En savoir plus sur Dates and Time dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!