Formatting Dates for Display

Problem

You need to format dates or time for output.

Solution

Use the date command with a strftime format specification. See “Date and Time String Formatting with strftime” in Appendix A or the strftime manpage for the list of format specifications supported.

# Setting environment variables can be helpful in scripts:
$ STRICT_ISO_8601='%Y-%m-%dT%H:%M:%S%z'   # http://greenwichmeantime.com/info/iso.htm
$ ISO_8601='%Y-%m-%d %H:%M:%S %Z'         # Almost ISO-8601, but more human-readable
$ ISO_8601_1='%Y-%m-%d %T %Z'             # %T is the same as %H:%M:%S
$ DATEFILE='%Y%m%d%H%M%S'                 # Suitable for use in a file name

$ date "+$ISO_8601"
2006-05-08 14:36:51 CDT

gawk "BEGIN {print strftime(\"$ISO_8601\")}"
2006-12-07 04:38:54 EST

# Same as previous $ISO_8601
$ date '+%Y-%m-%d %H:%M:%S %Z'
2006-05-08 14:36:51 CDT

$ date -d '2005-11-06' "+$ISO_8601"
2005-11-06 00:00:00 CST

$ date "+Program starting at: $ISO_8601"
Program starting at: 2006-05-08 14:36:51 CDT

$ printf "%b" "Program starting at: $(date '+$ISO_8601')\n"
Program starting at: $ISO_8601

$ echo "I can rename a file like this: mv file.log file_$(date +$DATEFILE).log"
I can rename a file like this: mv file.log file_20060508143724.log

Discussion

You may be tempted to place the + in the environment variable to simplify the later command. On some systems the date command is more picky about the existence and placement of the + than on others. Our advice is to explicitly add it to the date command itself.

Many more formatting options ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.