How to convert datetime to day of the year when there are more than one year?
25 次查看(过去 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
另请参阅
类别
在 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!