Using GNU Date for tricky date/time manipulations
I love shell scripting. This is something that the typical Windows users usually do not understand. They have to download tons of buggy shareware utilities to do something simple. In UNIX you can do a lot of tricky things with the standard tools that come with the system (in case of Linux - for free). One of the tools that is much more powerful than one may think is GNU “date” program. This article provides a number of examples of using this command.
With GNU date you can:
- Format any date into the string
- Set the system date
- Perform the simple date/time calculations (adding/subtracting)
### #1 - Formatting the current time
You can use a number of different format specifiers to get the desired result. Note that “-“ flag is used to disable the padding with leading 0s.
$ date +"Today is %F, %A, %-jth day of the year, exactly %H:%M:%S.%N" Today is 2008-01-23, Wednesday, 23th day of the year, exactly 21:27:55.240788882
### #2 - Converting the time to the UNIX timestamp (milliseconds since epoch)
Extremely useful operation since it allows you to perform some other manipulations with the result, like aligning it, for example.
$ date +"%s" 1201141803
### #3 - Converting UNIX timestamp into the date
This and some other examples use “-d” option. If this option is not used, the date command always deals with the current system time. If it is used - it deals with the date/time provided by you. This example uses the date's ability to modify the date by adding some date/time units.
$ date -d "1970-01-01 00:00:00 UTC + 1201141803 seconds" Wed Jan 23 21:30:03 EST 2008
If you pass “-u” option, the result will be in UTC:
date -d "1970-01-01 00:00:00 UTC + 1201141803 seconds" -u Thu Jan 24 02:30:03 UTC 2008
#4 - Formatting date to multi-line string
$ date +"Year: %Y%nMonth: %m%nDay: %d" Year: 2008 Month: 01 Day: 23
#5 - Calculating file age using date
$ echo "/bin has been last modified $(expr ( `date +%s` - `date -r /bin +%s` ) / 3600) hour(s) ago" /bin has been last modified 358 hour(s) ago
#6 - Calculating time till midnight
$ echo "$(expr ( `date -d "00:00:00 + 1 day" +%s` - `date +%s` ) / 60 ) minute(s) till midnight ($(date))" 110 minute(s) till midnight (Wed Jan 23 22:09:36 EST 2008)
This example may require some explanations. The first “date” command takes the current date, replaces the time with 00:00:00 and adds one day - this makes the today's midnight. Then we calculate the difference between the timestamp of the coming midnight and the current timestamp and divide it by 60.
Have fun with the dates (and do not forget about the time zones) !
blog comments powered by Disqus