Monday, December 8, 2014

Getting Yesterdays or Tomorrows Day With Bash Shell Date Command

Getting Yesterdays or Tomorrows Day With Bash Shell Date Command


When invoked without arguments, the date command displays the current date and time. Depending on the options specified, date will set the date and time or print it in a user defined way. I've seen many sysadmin writing perl scripts for calculating relative date such as yesterdays or tomorrows day. You can use GNU date command, which is designed to handle relative date calculation such as:
  • 1 Year
  • 2 Days
  • 2 Days ago
  • 5 Years
The syntax is as follows:
 
date  --date="STRING"
date  --date="next Friday"
date  --date="2 days ago"
 
The --date=STRING is a human readable format such as "next Thursday" or "1 month ago". A date string may contain items indicating calendar date, time of day, time zone, day of week, relative time, relative date, and numbers.

Why Use Relative GNU/date Formats?

  • Ease of use
  • Write your own shell scripts
  • Automate task using cron (example run a job on last day of the month or Nth day of the month or 3rd Friday and so on)

Examples

First, to display today's date, enter:
$ date
Sample outputs:
Wed Jun 15 04:47:45 IST 2011
To display yesterday's date, enter:
$ date --date="1 days ago"
OR
$ date --date="1 day ago"
OR
$ date --date="yesterday"
OR
$ date --date="-1 day"

No comments:

Post a Comment

  How to Change Instance Type & Security Group of EC2 in AWS By David Taylor Updated April 29, 2023 EC2 stands for Elastic Compute Cloud...