How to create datetime from day of year?

조회 수: 28 (최근 30일)
Bruce Elliott
Bruce Elliott 2015년 9월 24일
댓글: Peter Perkins 2015년 9월 25일
I know that I can get a date from a datetime object as YYYY-DDD, but what if I want to create a datetime object, given the year and day-of-year?
I've done this: >> T = datetime(2015,1,1) + days(266);
but is there a more direct way?
  댓글 수: 1
Peter Perkins
Peter Perkins 2015년 9월 25일
It's worth noting that as long as you don't opt into time zones, the above works, but in general what you'd want is datetime(2015,1,1) + caldays(266). day(1) is just another way of saying hours(24), whereas caldays(1) is really "one day on the calendar" and accounts for daylight saving changes.

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

채택된 답변

Steven Lord
Steven Lord 2015년 9월 24일
The day, month, and year numbers you input into DATETIME don't need to be within the normal ranges for those numbers (1 to 12 for month, 1 to 28/29/30/31 for day depending on the month, etc.) For instance, September 24th 2015 is the 267th day of the year.
>> datetime(2015, 1, 267)
ans =
24-Sep-2015
There is some precedence for this, including some in MATLAB itself.
A = magic(4);
A(5) % A only has 4 rows but this linear index wraps around and refers to A(1, 2)
  댓글 수: 1
Bruce Elliott
Bruce Elliott 2015년 9월 25일
Thanks, Steven! I should have guessed that would work.
Thanks for the links, as well - also excellent references. ;-)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by