How do you convert POSIX date to day of year?

As ?POSIXlt reveals, a $yday suffix to a POSIXlt date (or even a vector of such) will convert to day of year. Beware that POSIX counts Jan 1 as day 0, so you might want to add 1 to the result.

It took me embarrassingly long to find this, so I thought I'd ask and answer my own question.

Alternatively, the excellent lubridate package provides the yday function, which is just a wrapper for the above method. It conveniently defines similar functions for other units (month, year, hour, ...).

today <- Sys.time()
yday(today)

An alternative is to format the "POSIXt" object using strftime():

R> today <- Sys.time()
R> today
[1] "2012-10-19 19:12:04 BST"
R> doy <- strftime(today, format = "%j")
R> doy
[1] "293"
R> as.numeric(doy)
[1] 293

which is preferable to remembering that the day of the years is zero-based in the POSIX standard.

Tags:

Datetime

R