How to find the day number of any year from a date?

150 ビュー (過去 30 日間)
Md. Golam Mostafa
Md. Golam Mostafa 2015 年 7 月 23 日
編集済み: Sergey Kostrukov 2022 年 2 月 12 日
I am very new in programming and therefore it is probably a novice's question. I have to write a script that takes a number of day(dd), month(mm) and year(yyyy)values arranged in three separate columns of a MATLAB variable and gives the day number of the year(e.g. for 03 March 2012, 31+29+3=63) as output.
  2 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2015 年 7 月 23 日
Can you explain?
Md. Golam Mostafa
Md. Golam Mostafa 2015 年 7 月 23 日
I have a variable in the workspace containing all the data. Column 1 stores the day(dd), column 2 month (mm) and column 3 year (yyyy). I need to find the day number (for example, for 02/01/2012 day number=2, for 03/03/2012 day number=Jan (31)+ Feb (29)+ Mar (03)=63). The day number is 63. But for 03/03/2013 day number=Jan (31)+ Feb (28)+ Mar (03)=62). I need output of each date in a separate variable.

サインインしてコメントする。

採用された回答

Peter Perkins
Peter Perkins 2015 年 7 月 23 日
If you are using R2014b or later, the datetime data type allows you to compute the day of year using the day function:
>> x = [2012 1 2; 2012 3 3; 2013 3 3]
x =
2012 1 2
2012 3 3
2013 3 3
>> d = datetime(x)
d =
02-Jan-2012
03-Mar-2012
03-Mar-2013
>> day(d,'dayofyear')
ans =
2
63
62
  2 件のコメント
Md. Golam Mostafa
Md. Golam Mostafa 2015 年 7 月 24 日
I am running this code but it shows an error of this kind.
??? Undefined function or method 'datetime' for input arguments of type 'double'.
Error in ==> testdaynum1 at 32 d = datetime(YMD);
What is the solution?
Peter Perkins
Peter Perkins 2015 年 7 月 24 日
Presumably, you are not "using R2014b or later". datetime did not exist prior to that.

サインインしてコメントする。

その他の回答 (3 件)

Andrei Bobrov
Andrei Bobrov 2015 年 7 月 24 日
x = [2012 1 2; 2012 3 3; 2013 3 3];
d = datenum(x);
out = d - datenum(year(d),1,1) + 1;

Jos (10584)
Jos (10584) 2015 年 7 月 23 日
help datenum
and then use simple subtraction

Sergey Kostrukov
Sergey Kostrukov 2022 年 2 月 12 日
編集済み: Sergey Kostrukov 2022 年 2 月 12 日
Fractional value of days since biginning of the year (0-364.9999):
daysFrac = days(currentTime - datetime(year(currentTime), 1, 1, TimeZone=currentTime.TimeZone))
To get the whole number starting from 1 (i.e. day index):
floor(daysFrac + 1)

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by