Convert day of year to Date?

I want help converting 1 to 1st Jan; 365 to 31st Dec and so on. Basically I want to convert day number of a year into the actual date it corresponds to. Any help will be greatly appreciated. I have done the inverse using the following code
d = datetime('20-Mar-2018')
Dn = day(d,'dayofyear')

 Risposta accettata

Pratyush Das
Pratyush Das il 2 Ago 2018
I finally found the answer I was looking for.
N=10; %you can input any other number,The day in question is the 'N'th day of the year
Dt=datetime('1-Jan-2018')+N-1 % This code will give the date of the 'N'th day.

Più risposte (2)

Steven Lord
Steven Lord il 31 Lug 2018
You want to convert the day number to the date in the current year?
% Get today and the start of the current year
d = datetime('today');
s = dateshift(d, 'start', 'year');
% One approach is to add 77-1 to s (1 January, day 1) to get to day 77
day77a = s + 77 - 1
check_a = day(day77a, 'dayofyear')
% Another approach, shift s to the start of day 77-1 after s
day77b = dateshift(s, 'start', 'day', 77-1)
check_b = day(day77b, 'dayofyear')
% A third approach, create "January 77th" of the current year
day77c = datetime(year(d), 1, 77)
check_c = day(day77c, 'dayofyear')
Pratyush Das
Pratyush Das il 2 Ago 2018
I finally found the answer I was looking for. Suppose the Day in question is the 'N'th day of the year. Then the following code will give the exact date corresponding to that day.
Dt=datetime('1-Jan-2018')+N-1

5 Commenti

Sort of. If you are working with timezones, best to use
Dt = datetime(year,1,0) + caldays(N)
to account for the fact that twice a year, the day is not 24 hours. But if you already know the year, why not just
dt = datetime(year,1,N)
Sreeraj T
Sreeraj T il 10 Mar 2021
@Peter Perkins, this is nice suggestion. I have a question in this regard: in my data I know that year is 2019, which implies that 307 corresponds to 03-Nov-2019.
I also do have another number ' 307.234426997'. How can I convert extract time from it?
Thanks in advance.
jeremy
jeremy il 11 Ott 2022
307.234426997 = the 307th day and .234426997 of that day. To convert the decimal to a time multiply
24 * .234426997 = 5.626247928 which means 5 am and change.
60 * .626247928 = 37.57487568 which means 37 mins and change.
60 * .57487568 = 34.4925408
So the full timestamp would be '2019-11-03 05:37:34.493'
You could split the function into the integer part 307 and the fractional part 0.234426997 using floor and subtraction.
x = 307.234426997
x = 307.2344
numFullDays = floor(x)
numFullDays = 307
numPartialDays = x - numFullDays
numPartialDays = 0.2344
dt2 = datetime(2019, 1, numFullDays) + days(numPartialDays)
dt2 = datetime
03-Nov-2019 05:37:34
dt2.Format = dt2.Format + ".SSSSSS"
dt2 = datetime
03-Nov-2019 05:37:34.492540

Accedi per commentare.

Categorie

Community Treasure Hunt

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

Start Hunting!

Translated by