Pages

Sunday, August 31, 2014

More GNU date magic


More GNU Date Magic


Many unix users don't realise that the  GNU date utility can be used for far more than simply getting and setting the time.
GNU date is a very versatile and handy utility for calculating, formatting and manipulating dates generally.

One of the things you need to know about that is that you can set the time and date that you want date to work on.

Basically there are two dates that date works with:

  • now i.e. the time and date of execution or
  • some other arbitrary date specified by the caller


To use now you often will not need to specify anything

e.g.
[jtan@clivm 0509]$ date
Mon Sep  1 11:50:28 CST 2014 

returns the time and date that you executed the command.
In this case 11:50 and 28 seconds on Monday Sep 1 2014 CST (Central Standard Time)

But if I want to know the date for 60 days in the future and I am too lazy too count the days in the calendar or I want to use that in a script I can tell date to print that time.

The way you tell date to do it's work based on a time other than now is to use the -d option.

Now the real date magic is that the -d option is very flexible in the format of the options it will accept.

e.g. to find out the date and time 60 days from when I run the command I can run:
 date -d  "now +  60 days"
and it will give me
[jtan@clivm 0509]$ date -d "now + 60 days"
Fri Oct 31 12:55:48 CST 2014

Now I have used the keyword now to indicate that I want date to run using the time of execution as it's base time to use.

However that is actually redundant in this case, because now is actually the default, so date -d "+60 days" will also work. In fact date -d"60 days" will also work, which I think is about as minimal as you can go and still express the desired result.

You can of course also pass date a format in the standard manner:

[jtan@clivm 0509]$ date -d "now 1 month"  "+%d-%m-%Y"
01-10-2014





No comments:

Post a Comment