Wednesday, September 15, 2010

Trick and Tips when bash script dealing date

This is some tricks and tips I found when I searching around google.

Getting Yesterdays or Tomorrows day with 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 people writing a perl script for calculating yesterday or tomorrow. Computer loves numbers but we love relative terms like 2 days ago. Luckily GNU date command is designed to handle relative date calculation.

Why use relative date formats?

* Ease of use
* To write your own 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)

First, print today's date:
$ date
Sun Jun 17 12:17:24 CDT 2007

Now display Yesterday's date:
$ date --date="1 days ago"
OR try:
$ date --date="yesterday"
Sat Jun 16 12:17:20 CDT 2007

Now display Tomorrow's date:
$ date --date="-1 days ago"
Or better try:
$ date --date="next day"
Sat Jun 16 12:17:20 CDT 2007
Getting date in the future

To get tomorrow and day after tomorrow (tomorrow+N) use day word to get date in the future.
Getting date in the past

To get yesterday and earlier day in the past use string day ago:
Moving by whole years or months

You can add year and months keywords to get more accurate date:
$ date --date='2 year ago' # past
$ date --date='3 years' # go into future
$ date --date='2 days' # future
$ date --date='1 month ago' # past
$ date --date='2 months' # future
Moving date using more precise units

* You can use fortnight for 14 day
* Week for 7 days
* hour for 60 minutes
* minute for 60 seconds
* second for one second
* You can also use this / now / today keywords to stress the meaning

To print the date of this Friday:
$ date --date='this Friday'
To print the date of the day six months and 15 day
$ date --date='6 months 15 day'
To print the date of the day two months and 5 days ago:
$ date --date='2 months 5 day ago'

You can also use relative format to setup date and time. For example to set the system clock forward by 30 minutes, enter:
# date --set='+30 minutes'

To display date in epoch time:
$ date --date='1970-01-01 00:00:01 UTC +5 hours' +%s

Source : http://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html

No comments:

Post a Comment

Feel free to leave your question or comment here, we will reply you as soon as possible.