Oneliner: play with dates

If you need to work with dates in a shell script, this oneline could be useful:

echo $((`date +%s` - $OFFSET))|awk '{print strftime("%Y-%m-%d",$1)}'

What it does: it takes the current system time, converts it to epoch, rest $OFFSET (which should be in seconds) and then convert it again in the forma YYYY-MM-DD (but you can use every output supported by strftime, man strftime). Useful if you want to do some quick date calculation without having to fight with months, leap years and so on.

Advertisement

One thought on “Oneliner: play with dates

  1. Nice trick — I didn’t know about awk’s strftime. But you can do some of the same things with GNU’s date too:

    $ date -d ‘2 seconds ago’ +’%Y-%m-%d-%H-%M-%S’

    2007-09-04-06-22-48

    $ date -d ‘+4 days’ +’%Y-%m-%d-%H-%M-%S’

    2007-09-08-06-23-14

    I’m definitely going to remember strftime for when I don’t have GNU date, though.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s