Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get day of the year in shell?

How can I get the day of the year in shell?

date '+%V' will give me the week of the year, which is 15 for today; but I need to find the day of the year!

like image 272
Reza Toghraee Avatar asked Apr 11 '12 19:04

Reza Toghraee


3 Answers

From the coreutils date manual:

%j     day of year (001..366) 
like image 93
Mat Avatar answered Nov 01 '22 10:11

Mat


Use the date command and the %j option...

doy=$(date +%j) 
like image 37
Peter.O Avatar answered Nov 01 '22 09:11

Peter.O


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.

If you are looking for a proper POSIX-portable solution for getting the day number of arbitrary dates, the least unattractive solution might be to create your own program. If you can rely on Python or Perl (or GNU Awk) to be installed, those make it relatively easy, though it's still a bit of a chore using only their default libraries.

like image 34
tripleee Avatar answered Nov 01 '22 10:11

tripleee