Search code examples
rdatestrptime

When converting decimal date to julian with %j strptime, how do you specify the year?


This code causes the julian year to default to the current year, but how can I specifiy that the year should be 2011?

fractionalDayofYear <-seq(300,302,0.1)
julianDate<-  format(strptime((fractionalDayofYear), format='%j'),'%Y-%m-%d')

Solution

  • Use as.difftime to add the days + fractional days more accurately:

    as.POSIXct("2010-12-31", tz="UTC") + as.difftime(fractionalDayofYear, units="days")
    #[1] "2011-10-27 00:00:00 UTC" "2011-10-27 02:24:00 UTC" "2011-10-27 04:48:00 UTC" ...
    

    If you don't care about the part days, then just paste a "2011" in there:

    as.Date(paste("2011",fractionalDayofYear), format="%Y %j")
    # [1] "2011-10-27" "2011-10-27" "2011-10-27" "2011-10-27" "2011-10-27" ...