Linux Date Command – How to Use Day of Year as Input Format

datelinux

Using the command

$ date +%j

gives an output of the day of the year (001-366).
However I need to use the day of the current year as an input format i.e.

$ date --date='066 day'  +%F

Which for year 2021 I would expect 2021-03-07 as the output. Instead I get 2021-05-13. Does anyone know what is going on and if there is a way to get what I want using date.

Best Answer

To get the 66th day of the year with GNU date:

$ date --date='jan 1 + 65 days' +%F
2021-03-07

or

$ date --date='dec 31 last year + 66 days' +%F
2021-03-07

With date --date='066 day' +%F you get the date 66 days from today. On the 8th of March, this happens to be the 13th of May.


The above uses GNU date. On OpenBSD (not that you asked, but anyway), you could do something like the following:

$ date -u -r "$(( $(date -ju -f %m%d 0101 +%s) + 65*86400 ))" +%F
2021-03-07

which would be somewhat similar to the first GNU date command above in that it adds some time from January 1st.