Wednesday, January 4, 2012

Date command in Linux

Man page of date will give you more info than anything else, it is a very descriptive one.
I wanted to hightlight few of the options used and thier alternatives, mainly the option "-d". Why because it looks like solaris version of date does not have "-d" option.

The man page says

       -d, --date=STRING
              display time described by STRING, not `now'

Lets take few examples

Firing the date command would give you the date

Code:
root@bt > date
Wed Jan  4 07:52:17 IST 2012

Do you want to customize this? No problem. Use the format control. There are like more than 20 format control options.

Say, you want the date in DD/MM/YYYY format

Code:
root@bt > date '+%d/%m/%Y'
04/01/2012

       %d     day of month (e.g, 01)
       %m     month (01..12)
       %Y     year

Want the current date in seconds since the epoch? Use "+%s" option

Code:
root@bt > date '+%s'
1325644010

       %s     seconds since 1970-01-01 00:00:00 UTC

As you can see, "+" is mandatory which is followed by the format specifier.

To set/change the system date, use the "-s" option.

       -s, --set=STRING
              set time described by STRING

Code:
root@bt > date
Wed Jan  4 08:21:47 IST 2012

root@bt > date -s "Mon Dec 31 00:00:00 IST 1990"
Mon Dec 31 00:00:00 IST 1990

root@bt > date
Mon Dec 31 00:00:01 IST 1990

Now, what does "-d" option do? Hmmm, if you see we were dealing with current system date till now. What if you want to do the same with some other date? Well, that is where "-d" option comes to the rescue!

Say, you want to find the seconds since epoch till December 31 1990

Code:
root@bt > date -d "Dec 31 1990" '+%s'
662581800

You want to format a date given to you in "31 Dec 1990" to MM-DD-YY

Code:
root@bt > date -d "31 Dec 1990" '+%m-%d-%y'
12-31-90

Cool right? Now, the "-d" option is not available in Solaris (not sure about 10 though).
Here is an alternative in awk for achieving the above

To get the time in seconds

Code:
root@bt > echo "Dec 31 1990" | nawk 'BEGIN{month="JanFebMarAprMayJunJulAugSepOctNovDec"}
{ print mktime($3" "int((index(month,$1)/3))+1" "$2" 00 00 00") }'
662581800

Code:
root@bt > echo "31 Dec 1990" | nawk 'BEGIN{month="JanFebMarAprMayJunJulAugSepOctNovDec"}
{ print int((index(month,$2)/3))+1"-"$1"-"substr($3,3) }'
12-31-90

We can practically do anything in awk! Check the right side link for AWK tutorial.

One more thing before we go, how do we convert the seconds to date?
Say, I have 662581800 (from our previous example), I want to convert it to actual date format

Code:
root@bt > date -d @662581800
Mon Dec 31 00:00:00 IST 1990

Note the "@" symbol before the seconds.

Also note that I have used nawk instead of awk, because in solaris the awk version is pretty old and it is kind of useless. Either use "nawk" or awk from this path "/usr/xpg4/bin/awk" in solaris.

Good Day!

No comments:

Post a Comment