DEV Community

Cover image for Bash: Some useful tricks with date command
Rehan Qadir
Rehan Qadir

Posted on • Updated on

Bash: Some useful tricks with date command

Lets get started

Just typing date will print the date and time on the standard output. Following are some useful options with the date command.

  • Seconds since UNIX epoch (01/01/1970)

Use %s to get number of seconds passed since UNIX epoch. Creating unique file names is one of the possible use case.

# + is use for formatting
date +%s
# Output: 1589455968
Enter fullscreen mode Exit fullscreen mode
  • Number of days since the year's beginning

Use %j to get the number of days passed since the beginning of the year.

# + is use for formatting
date +%j
# Output: 135
Enter fullscreen mode Exit fullscreen mode
  • Dates in the past or future

Use -d or --date option to get any date in the past or future.

# + is use for formatting
date +%F -d "1 day ago"
# Output: 2020-05-13

# More easily by using - sign
date +%F -d "-1 day"
# Output: 2020-05-13

date +"%D %T" -d "1 year ago"
# Output: 05/14/19 16:54:02

date +"%F" --date="1 month ago"
# Output: 2020-04-14

# For dates in future use + sign before number
date +%F -d "+1 day"
# Output: 2020-05-15
Enter fullscreen mode Exit fullscreen mode
  • Get Time Zone

Use %Z option to get your time zone

# + is use for formatting
date +%Z
# Output: PKT
Enter fullscreen mode Exit fullscreen mode
  • Get date from UNIX epoch

To extract date from the number of seconds passed since UNIX epoch, use -d with @.

date -d @1500000000
# Output: Fri 14 Jul 07:40:00 PKT 2017
Enter fullscreen mode Exit fullscreen mode
  • Get date in ISO Format

Use -Iseconds option to get current date in ISO Format.

date -Iseconds
# Output: 2020-05-14T17:18:22+05:00
Enter fullscreen mode Exit fullscreen mode
  • Get the last day of the previous month

While executing an SQL command to retrieve data for the starting and ending date of the previous month, it is always a point of concern to correctly determine whether the previous month was of 30 or 31 days. To resolve this issue, we can use date in the option argument of date command with %d option to get the current day of the month.

# + is use for formatting
# %d is used to get the day of the month

date +%F -d "$(date +%d) days ago"
# Output: 2020-04-30
Enter fullscreen mode Exit fullscreen mode

I hope it will help you. Keep coding!

P.S. I will keep on adding to this post with time.

Top comments (1)

Collapse
 
waylonwalker profile image
Waylon Walker

Dates can be so hard!