Tuesday, May 15, 2012

GNU dates and strings conversion in Linux



 In one of our articles, we discussed about the GNU date command and the powerful options it has. In this article, we will see about the -d option in detail. -d option in date command can take multiple forms. Basically, it  takes a STRING and converts it to a date. And the STRING can be given in many different forms which makes the dates computation much easier. Let us see in detail with examples.

1. To convert a string "08-May-2012" to a UNIX date:
$ date -d "08-May-2012"
Tue May  8 00:00:00 IST 2012
     The output will look like as if the date command is fired on 8-May 2012. The -d option can take the string with - separated format as well. As shown , the string here takes the form  MM-Mon-YEAR format and gives the Unix date as output..

2. To format the above date output to a time stamp:
$ date -d "08-May-2012" '+%y%m%d'
120508
     %y gives YY, %m is number of the month and %d gives day.

3. The same timestamp can also be obtained with slash separated output:
$ date -d "08-May-2012" '+%y/%m/%d'
12/05/08
4. -d can also take hours, minutes and seconds and without the - symbol as well as shown below.
$ date -d "08 May 2012 11hours 30mins" '+%y%m%d%H%M'
1205081130
   In this example, it gives a date string for the date equivalent: "08 May 2012 11hours 30mins"

5. -d can take the switch mins as well as minutes.
$ date -d "08 May 2012 11AM 30minutes" '+%y%m%d%H%M'
1205081130
6. To convert date string present in shell variables,  the same option does the trick. If the date is in a variable in UNIX :
$ var="08 May 2012 11hours 30mins"
$ date -d "$var" '+%y%m%d%H%M'
1205081130
7. The hours, minutes and seconds can also be given in the colon separated format as well:
$ var="08-May-2012 11:24:25"
$ date -d "$var" '+%y%m%d%H%M%S'
120508112425
8. To get yesterday's date:
$ date -d "-1 day"
Wed May  9 08:04:50 IST 2012
9.  Also, if you simply give "yesterday" with the -d switch, the previous day's date will be given.
$ date -d "yesterday"
Wed May  9 08:04:40 IST 2012
    As discussed in our earlier date article, in place of "yesterday", we can also give "1 day ago".

  10. To find the date of the next Monday :
$ date -d "Monday"
OR
$ date -d "next Monday"
11. Similarly, to find the date of last Monday:
$ date -d "last Monday"
12. In the same lines, to find the date of next year:
$ date -d "next year"
  In the same lines, we can find the dates of "next week", "next month", etc as well.

13. To get the date of 5 days from now:
$ date -d "5 days"
14. To get the date of 10 days from next Monday:
$ date -d "next Monday +10days"
15. To get the timestamp of a specific time: say Friday, 8PM 19minutes and 20 seconds:
$ date -d "Friday 8PM 19minutes 20seconds"
Fri May 11 20:19:20 IST 2012
    This can be formatted as explained earlier.

Reference: man date

No comments:

Post a Comment