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')
"
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 are available, see the date manpage or the C strftime() function (man 3 strftime) on your system for a full list.

Unless otherwise specified, the time zone is assumed to be local time as defined by your system. The %z format is a nonstandard extension used by the GNU date command; it may not work on your system.

ISO 8601 is the recommended standard for displaying dates and times and should be used if at all possible. It offers a number of advantages over other display formats:

  • It is a recognized standard

  • It is unambiguous

  • It is easy to read while still being easy to parse programmatically (e.g., using awk or cut)

  • It sorts as expected when used in columnar data or in filenames

Try to avoid MM/DD/YY or DD/MM/YY or even worse M/D/YY or D/M/YY formats. They do not sort well and they are ambiguous, since either the day or the month may come first depending on geographical location, which also makes them hard to parse. Likewise, use 24-hour time when possible to avoid even more ambiguity and parsing problems.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.33.41