When you type the basic date command into a Linux terminal, the system outputs the current date and time in a standard, pre-configured format (e.g., Thu Oct 26 14:32:10 UTC 2023). While this is perfectly fine for a human glancing at the screen, it is a nightmare if you are writing a bash script to generate automated database backups and need a precise, machine-readable timestamp (like 2023-10-26) to append to the filename. Fortunately, the Linux date command includes a powerful formatting engine that allows you to extract and display time in almost any conceivable structure.
Using Format Specifiers
To control the output of the date command, you must use a plus sign (+) followed immediately by specific format specifiers (which all begin with a percent sign %).
- Open your Linux terminal.
- Type the command:
date +"%Y-%m-%d" - Press Enter.
The terminal will output exactly: 2023-10-26. Notice how the command completely ignored the day of the week, the time zone, and the exact time, outputting only the specific numerical data we requested, separated by the hyphens we hardcoded into the string.
Essential Date Formatting Codes
Here are the most critical format specifiers you will use when scripting:
%Y: The full 4-digit year (e.g., 2023).%y: The 2-digit year (e.g., 23).%m: The month as a two-digit number (01 to 12).%b: The abbreviated month name (Jan, Feb, Mar).%d: The day of the month (01 to 31).%H: The hour in a 24-hour military clock (00 to 23).%M: The minute (00 to 59).%S: The precise second (00 to 59).
Common Scripting Use Cases
By combining these specifiers, you can generate exact strings for different use cases.
Scenario 1: Creating a Backup Filename
If you want to create a tarball archive of your website and ensure the filename includes the exact second it was generated, you would use a continuous string of numbers.
date +"%Y%m%d_%H%M%S"
Output: 20231026_143210. In a bash script, this looks like: tar -czvf backup_$(date +"%Y%m%d_%H%M%S").tar.gz /var/www/html
Scenario 2: Generating a Human-Readable Log Entry
If you are writing data to a text log file and want it to look neat, you can inject spaces and colons into the format string (which is why wrapping the format string in quotes is highly recommended).
date +"[%Y-%m-%d %H:%M:%S]"
Output: [2023-10-26 14:32:10]
Converting Unix Epoch Time
Computers do not actually track time using months and years; they track time using the “Unix Epoch”—the exact number of seconds that have elapsed since January 1, 1970. Occasionally, a system log will spit out a 10-digit number like 1698330730 instead of a date.
You can use the date command with the -d (date) flag to translate this raw Epoch number back into human-readable text.
date -d @1698330730
This will instantly translate the machine code back into a standard date string, allowing you to troubleshoot when an event actually occurred.