I can't figure out how to turn Sys.Date() into a number in the format YYYYDDD. Where DDD is the day of the year, i.e. Jan 1 would be 2016001 Dec 31 would be 2016365
Date <- Sys.Date() ## The Variable Date is created as 2016-01-01
SomeFunction(Date) ## Returns 2016001
Julian date. This format of date is a combination of year plus a relative day number within the year, which is more correctly called an ordinal date. A typical example is 2013-348 in the format YYYYDDD. This is equivalent to a calendar date of December 14 th 2013.
Assuming that the date is in cell A1, here is the Excel formula to convert Gregorian dates to JDE Julian: =(YEAR(A1)-1900)*1000+A1-DATE(YEAR(A1),1,1)+1.
Today's date is 05-Nov-2022 (UTC). Today's Julian Date is 22309 .
You can just use the format
function as follows:
format(Date, '%Y%j')
which gives:
[1] "2016161" "2016162" "2016163"
If you want to format it in other ways, see ?strptime
for all the possible options.
Alternatively, you could use the year
and yday
functions from the data.table
or lubridate
packages and paste them together with paste0
:
library(data.table) # or: library(lubridate)
paste0(year(Date), yday(Date))
which will give you the same result.
The values that are returned by both options are of class character. Wrap the above solutions in as.numeric()
to get real numbers.
Used data:
> Date <- Sys.Date() + 1:3
> Date
[1] "2016-06-09" "2016-06-10" "2016-06-11"
> class(Date)
[1] "Date"
Here's one option with lubridate
:
library(lubridate)
x <- Sys.Date()
#[1] "2016-06-08"
paste0(year(x),yday(x))
#[1] "2016160"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With