How to convert datetime to day of the year when there are more than one year?
조회 수: 24 (최근 30일)
이전 댓글 표시
Hi!
If I have an array of datetime like this -
'2003-10-14'
'2003-11-07'
'2003-11-15'
'2003-11-23'
'2004-01-10'
'2004-04-07'
'2004-10-08'
'2005-01-04'
'2005-01-20'
'2005-05-28'
'2005-06-05'
'2005-09-17'
'2005-11-20'
'2006-02-08'
'2006-02-16'
'2006-02-24'
'2006-03-04'
'2006-03-12'
How can I convert this datetime array as the day of the year? My day of the year should start from 2003-01-01 (= day 01). Once I reach 2004-01-01, it should be day 366. For the 2005-01-01, it should be day 731 and so on. Can any one kindly tell me how can I convert the whole array into a day of the year array?
Any feedback from you will be highly appreciated!!
댓글 수: 0
채택된 답변
KSSV
2022년 12월 20일
댓글 수: 2
Les Beckham
2022년 12월 20일
You might want to also read about the caldays function: https://www.mathworks.com/help/matlab/ref/calendarduration.caldays.html
추가 답변 (1개)
Steven Lord
2022년 12월 20일
Let's look at your sample data.
data = {'2003-10-14'
'2003-11-07'
'2003-11-15'
'2003-11-23'
'2004-01-10'
'2004-04-07'
'2004-10-08'
'2005-01-04'
'2005-01-20'
'2005-05-28'
'2005-06-05'
'2005-09-17'
'2005-11-20'
'2006-02-08'
'2006-02-16'
'2006-02-24'
'2006-03-04'
'2006-03-12'};
dt = datetime(data);
What's the first date in your data array? I'm not going to assume it's the first element of data.
firstdate = min(dt)
What's the start of that first date's year?
firstOfYear = dateshift(firstdate, 'start', 'year')
How many calendar days have elapsed between the 1st of January of that earliest year and each element of your data?
elapsedTime = between(firstOfYear, dt, 'Days')
Let's convert that into double. Note I need to add 1 because elapsedTime is the time between January 1st and your data but you want the number of those dates. There's 0 days between January 1st and January 1st but January 1st is day 1 of the year.
d = caldays(elapsedTime)+1
댓글 수: 1
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!