How to convert datetime to day of the year when there are more than one year?
25 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
KSSV
on 20 Dec 2022
2 Comments
Les Beckham
on 20 Dec 2022
You might want to also read about the caldays function: https://www.mathworks.com/help/matlab/ref/calendarduration.caldays.html
More Answers (1)
Steven Lord
on 20 Dec 2022
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 Comment
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!