date - macOS


Overview

The date command in macOS is used to display or set the system date and time. It’s a versatile tool for managing and manipulating date and time information, suitable for both desktop and scripting environments. It can output the current date, set system date, or transform date formats, making it essential for scheduling tasks, automation scripts, and time logs.

Syntax

The basic syntax for the date command is:

date [option]... [+format]

Where +format specifies the output format of the date or time. Without this option, date will display the current system time in the default format.

Options/Flags

  • -u, --utc, --universal: Display or set the time in UTC (Coordinated Universal Time) rather than the local timezone.
  • -r file: Display the last modification time of file.
  • -R: Output RFC 2822 compliant date string, useful for email timestamps.
  • -d string, --date=string: Display the time described by string, not ‘now’.
  • +format: A format string starting with + to display the date in a custom format, where format might contain various sequences like %Y for year in four digits, %m for month, %d for day of the month, etc.

Examples

  1. Display Current Date and Time:

    date
    
  2. Show Date in Custom Format:

    date +"%Y-%m-%d %H:%M:%S"
    
  3. Display Date for a specific Timezone:

    TZ="America/New_York" date
    
  4. Convert Timestamp to Readable Format:

    date -r 1609459200
    
  5. Set System Date:

    sudo date -s "2023-03-14 10:32:00"
    

Common Issues

  • Permission Denied: When trying to set the system date, you need superuser privileges. Use sudo before the command.
  • Timezone Conflicts: When scripting across different time zones, explicitly set the timezone using TZ=timezone.
  • Format Confusion: Pay close attention to the format characters in +format; a wrong specifier can lead to misleading or incorrect output.

Integration

The date command can be combined with other tools for more advanced tasks. For example, logging time with echo:

echo "Job started at $(date)" >> job.log

Or, setting file timestamps in combination with touch:

touch -t $(date +%Y%m%d%H%M) filename
  • cal: Display a calendar of the current month or specified month/year.
  • uptime: Tell how long the system has been running along with the current time.
  • zdump: Timezone dumper useful for debugging timezone settings.

For more details, refer to the macOS system documentation or use man date in the terminal.