Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a date to YYYYDDD?

Tags:

date

datetime

r

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
like image 600
LanceS Avatar asked Jun 08 '16 17:06

LanceS


People also ask

What date format is Yyyyddd?

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.

How do you convert Julian date to Gregorian date?

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.

What is today's 3 digit Julian date?

Today's date is 05-Nov-2022 (UTC). Today's Julian Date is 22309 .


2 Answers

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"
like image 183
Jaap Avatar answered Sep 24 '22 03:09

Jaap


Here's one option with lubridate:

library(lubridate)
x <- Sys.Date()
#[1] "2016-06-08"
paste0(year(x),yday(x))
#[1] "2016160"
like image 28
RHertel Avatar answered Sep 22 '22 03:09

RHertel