how to get day of the year in shell?
POSIX mandates the format string %j
for getting the day of the year, so if you want it for today's date, you are done, and have a portable solution.
date +%j
For getting the day number of an arbitrary date, the situation is somewhat more complex.
On Linux, you will usually have GNU date
, which lets you query for an arbitrary date with the -d
option.
date -d '1970-04-01' +%j
The argument to -d
can be a fairly free-form expression, including relative times like "3 weeks ago".
date -d "3 weeks ago" +%j
On BSD-like platforms, including MacOS, the mechanism for specifying a date to format is different. You can ask it to format a date with -j
and specify the date as an argument (not an option), and optionally specify how the string argument should be parsed with -f
.
date -j 04010000 +%j
displays the day number for April 1st 00:00.The string argument to specify which date to examine is rather weird, and requires the minutes to be specified, and then optionally allows you to prefix with ((month,) day, and) hour, and optionally allows year as a suffix (sic).
date -j -f "%Y-%m-%d" 1970-04-01 +%j
uses -f format date
to pass in a date in a more standard format, and prints the day number of that.
There's also the -v
option which allows you to specify relative times.
date -j -v -3w +%j
displays the day number of the date three weeks ago.