Unix Linux date command tutorial with examples

The linux date command is used to display and set the date of the system.
To see the current date type the command “ date” on the terminal as shown the below

output

Linux date Format

Linux date format is as below

  • %Y: 4-digit year (e.g., 2023)
  • %y: 2-digit year (e.g., 23)
  • %m: 2-digit month (e.g., 07 for July)
  • %d: 2-digit day of the month (e.g., 01)
  • %H: 2-digit hour in 24-hour format (e.g., 13 for 1 PM)
  • %M: 2-digit minute (e.g., 30)
  • %S: 2-digit second (e.g., 45)
  • %A: Full weekday name (e.g., Monday)
  • %a: Abbreviated weekday name (e.g., Mon)
  • %B: Full month name (e.g., July)
  • %b: Abbreviated month name (e.g., Jul)
  • %Z: Timezone name (e.g., PDT)

You can compile the above as per your need

date +"%Y-%m-%d %H:%M:%S"

Date With optioins

The above command will display the current day, date, month, year, and time as shown above.

Option:
the date command can also be used with the format specified.
Each format is preceded by the + symbol and followed by the % operator and the format is described as a single character.
We want to see only the current month use format +%m. as shown below.

output

output is month 07

We want to see only the current month name using format +%h. as shown below.

output

is month of July

We can also combine both commands as:

output

output is month 07 is July

Unix linux set date

Use the date command with the -s option with the desired date

Syntax for set Date

Command for time in Linux/Unix

To display the current system time in Linux, you can use the date command with the appropriate format option. Here’s an example:

The %T format code is used to display the time in the format “HH:MM:SS”

If you want to display the time in a specific timezone, you can use the %Z format code along with the %T code. For example:

To display only the current hour and minute in Linux, you can use the date command with the %H and %M format codes. Here’s the command:

This command will provide the current system time in the format “HH:MM”, where HH represents the hour (in 24-hour format) and MM represents the minute.

shell script todays date

Open the editor and write the following commands

Save and close the file.

Give execute permissions to the script using the following command:

Now, you can run the script in the terminal:

The script will display today’s date in the format “YYYY-MM-DD”.

Convert Date Formats

You can convert a date from one format to another using the date command and specifying the desired format with the +%FORMAT option. For example, to convert a date from “YYYY-MM-DD” format to “DD/MM/YYYY” format:

Calculate Future or Past Dates

To calculate a future or past date, you can use the -d option with the date command and provide a relative date expression. For example, to find the date 7 days from today:

Read More

Linux and Unix echo command tutorial with examples