how to get day of the year in shell?
Asked Answered
G

3

24

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!

Gayelord answered 11/4, 2012 at 19:17 Comment(0)
F
34

From the coreutils date manual:

%j     day of year (001..366)
Frangipani answered 11/4, 2012 at 19:19 Comment(0)
S
32

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

doy=$(date +%j)
Sergius answered 11/4, 2012 at 19:27 Comment(0)
B
4

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.

Bushtit answered 8/9, 2021 at 8:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.