help writing a script that tells the day of the week

4 次查看(过去 30 天)
I need help writing a code that tells me the day of the week as well as the number of the day relative to the year. Ex: input form month/day/year: xx/xx/xxxx output should say something like: The date 08/31/2011 is the 243 day of the year and is a wednesday.
I have tried so many different things from Mathworks with no luck.

采纳的回答

Star Strider
Star Strider 2015-10-10
One way (not using datetime, since not everyone may have it):
InpStr = '08/31/2011';
YrStart = datenum(InpStr(end-3:end), 'yyyy');
dtnm = datenum(InpStr, 'mm/dd/yyyy');
[DayOfWkNum,DayOfWkStr] = weekday(dtnm,'long');
fprintf(1, '\n\tThe date %s is the %d day of the year and is a %s\n', InpStr, dtnm-YrStart+1, DayOfWkStr)
The date 08/31/2011 is the 243 day of the year and is a Wednesday
  2 个评论
bachir
bachir 2015-10-10
Star Strider, You the man! or woman...! I modified it a little to fit my style but thanks a lot

请先登录,再进行评论。

更多回答(2 个)

Peter Perkins
Peter Perkins 2015-10-10
... and another way, using datetime (if you have R2014b or later):
>> d = datetime('08/31/2011','InputFormat','MM/dd/yyyy')
d =
31-Aug-2011
>> day(d,'dayofyear')
ans =
243
>> day(d,'name')
ans =
'Wednesday'

Stephen23
Stephen23 2015-10-10
编辑:Stephen23 2015-10-12
The grammar pedants amongst us may appreciate my FEX submission datestr8601, which provides a day-of-the-year string with the correct ordinal suffix:
>> X = [2011,08,31];
>> [A,B,C] = datestr8601(X,'*ymd','nnn','DDDD')
A =
2011-08-31
B =
243rd
C =
Wednesday
>> sprintf('The date %s is the %s day of the year, and is a %s.',A,B,C)
ans =
The date 2011-08-31 is the 243rd day of the year, and is a Wednesday.

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by