Objective

The objective is to use bash shell to count days since a specific date until now ( today ).

Difficulty

EASY

Conventions

  • # - requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
  • $ - requires given linux commands to be executed as a regular non-privileged user

Instructions

The easiest way to perform days count since a specifics day is to first get a number of seconds since epoch time ( 1970-01-01 ) for both dates. As an example lets count number of days since 28.12.1999 until today 8.1.2018. Consider a following example:
$ echo $((($(date +%s)-$(date +%s --date "1999-12-28"))/(3600*24))) days
6586 days
Let's add little bit of readability to the above command by using variables. First, we get seconds since epoch time ( 1970-01-01 ) until now:
$ now=$(date +%s)
$ echo $now
1515370378
Next we do the same for the 28.12.1999 date:
past=$(date +%s --date "1999-12-28")
$ echo $past
946299600
Next, calculate the difference:
$ difference=$(($now-$past))
$ echo $difference
569070778
Lastly, convert the difference in seconds to days:
$ echo $(($difference/(3600*24)))
6586
All done. The same principle can be used to calculate days between any specific days. For example let's count days between 1.1.2017 and 31.12.2017 dates:
$ echo $((($(date +%s --date "2017-12-31")-$(date +%s --date "2017-1-1"))/(3600*24))) days
364 days
ARE YOU LOOKING FOR A LINUX JOB?
Submit your RESUME, create a JOB ALERT or subscribe to RSS feed on LinuxCareers.com.
LINUX CAREER NEWSLETTER
Subscribe to NEWSLETTER and receive latest news, jobs, career advice and tutorials.
DO YOU NEED ADDITIONAL HELP?
Get extra help by visiting our LINUX FORUM or simply use comments below.

You may also be interested in: