Pages

Wednesday, May 30, 2007

Fun With date(1) Command

-j flag is very very useful with the date(1)  command. it lets you do date math without messing with the system clock.

#!/bin/sh
now=`date -j +%Y%m%d%H%M`
newdate=` date -j -v+1D -v-2H ${now} +%Y%m%d%H%M`
echo ${now}
echo ${newdate}
This adds 1 day to the current date/time and subtracts 2 hours (yes I could have just done +22H instead) but this is for illustrative purposes. So now you can do date math without awk, perl, python etc. 

Useful format flags (man strftime(3) for full details)
  • %a - abbreviated weekday name
  • %b - abbreviated month name
  • %Y - yyyy
  • %H - hh in 0 padded 24 hour format
  • %j - day of the year
  • %M - MM 0 padded minute (00-59)
  • %m - mm 0 padded numeric month (01-12)
  • %S - SS 0 padded seconds (00-60)
  • %s - seconds since epoch
  • %u - numeric day of the week starting on Monday (1-7)
  • %Z - Time Zone Name
  • %z - time zone offset

No comments:

Post a Comment