Date conversion oneliners in bash

From lxadm | Linux administration tips, tutorials, HOWTOs and articles
Jump to: navigation, search

Some handy date conversion oneliners in bash.

  • Assuming we have a unix timestamp format (seconds since 1970-01-01 00:00:00 UTC) and we want to make it human readable:
$ date --date=@1343351724
Fri Jul 27 01:15:24 GMT 2012

  • Same as above, but we’d rather make the date output in a different format:
$ date --date=@1343351724 +%d/%b/%Y:%R:%S

  • Need the above for a different timezone? Try this:
$ env TZ="Asia/Tokyo" date --date=@1343351724 +%d/%b/%Y:%R:%S

  • Date “now” in Tokyo, our custom output format:
$ env TZ="Asia/Tokyo" date +%d/%b/%Y:%R:%S

  • 12 hours later from now in Tokyo:
$ env TZ="Asia/Tokyo" date +%d/%b/%Y:%R:%S --date="+12 hours"

For a list of possible timezones on your system, see ls /usr/share/zoneinfo.

  • date 30 days ago (useful i.e. to expire objects in the database):
$ date "+%F %R:%S" --date="30 days ago"
2014-11-08 17:03:49

  • First day of this month:
$ date +%F
$ date -d "-$(date +%d) days + 1 day" +%F

  • Last day 2 months ago:
$ date +%F
$ date -d "-$(date +%d) days - 1 month" +%F

  • Convert syslog date to unix timestamp – assuming your log line begins with:
Nov 5 08:49:45

you can convert it to unix timestamp with:

$ date --date="Nov 5 08:49:45" +%s