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
27/Jul/2012:01:15:24


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


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


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

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
2012-08-07
$ date -d "-$(date +%d) days + 1 day" +%F
2012-08-01


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


  • 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
1415173785