<<< Back to Tips Index

8th Dec 2015

Christmas!

Using GNU Date to work out how many days until a given event (such as Christmas - 25th December)

GNU's date tool offers a few additional features over the standard abilities of the traditional UNIX date facility. One of these is the "+%j" switch, which tells you the day's number as a day-of-the-year. So the first of January is "1", the second is "2", and so on. The first of February is "31", and Christmas is "359" - that is, it's the three-hundred-and-fifty-ninth day of the year (at least it is this year; it would be the 360th on a Leap Year).

The "-d dd-mmm" option allows you to specify a date other than today; it is remarkably clever in what it can understand. In this example, we just give it "25-Dec" which it will always interpret as "Christmas, this year".

This simple script takes the difference between today and Christmas this year, and tells you the time until Christmas.

Note that in the last week of the year, it will give you a negative number; you may want to tweak this to give the days until next Christmas.

Download christmas.sh

#!/bin/bash

TODAY=`date +%j`                 # Today, as day-of-year (1-366)
CHRISTMAS=`date -d 25-Dec +%j`   # Christmas day, in same format

echo "There are $(($CHRISTMAS - $TODAY)) days until Christmas."
Christmas
Steve's Bourne / Bash shell scripting tips
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon