0 0 votes
Article Rating

How do I format the date to display on the screen on for my shell scripts as per my requirements on Linux or Unix like operating systems?

You need to use the standard date command to format date or time in Linux or Unix shell scripts. You can use the same command with the shell script. This page shows how to format date in Linux or Unix-based system.

Tutorial details
Difficulty levelEasy
Root privilegesNo
Requirementsdate command
CategoryCommands
OS compatibilityFreeBSD • Linux • macOS • NetBSD • OpenBSD • Unix • WSL
Est. reading time8 minutes

ADVERTISEMENT

Linux Syntax To Format Date For Display On Screen

The syntax is as follows for the GNU/date and BSD/date command:
$ date +FORMAT
$ date +"%FORMAT"
$ date +"%FORMAT%FORMAT"
$ date +"%FORMAT-%FORMAT"
$ date -d "DATE STRING" +"%FORMAT"
$ TZ="TIMEZONE" date -d "DATE STRING" +"%FORMAT"

An operand with a leading plus (+) sign signals a user-defined format string which specifies the format in which to display the date and time. The following examples are tested on GNU/Linux, Apple OS X Unix, and FreeBSD unix operating system.

Task: Display date in mm-dd-yy format

Open a terminal and type the following date command:
$ date +"%m-%d-%y"
Sample outputs:

02-27-07

To turn on 4 digit year display:
$ date +"%m-%d-%Y"
Just display date as mm/dd/yy format:
$ date +"%D"

Task: Display time only

Type the following command:
$ date +"%T"
Sample outputs:

19:55:04

To display locale’s 12-hour clock time, enter:
$ date +"%r"
Sample outputs:

07:56:05 PM

To display time in HH:MM format, type:
$ date +"%H-%M"
Sample outputs:

00-50

How do I save time/date format to the shell variable?

Simply type the following command at the shell prompt to get the current date in MM-DD-YYYY format:
$ NOW=$(date +"%m-%d-%Y")
To display a variable use the following simple commands to output on screen under Linux and UNIX using the printf command/echo command:
$ echo "$NOW"
$ printf "%s\n" $NOW

A sample shell script

#!/bin/bash
NOW="$(date +"%m-%d-%Y")"
FILE="backup.$NOW.tar.gz"
echo "Backing up data to /nas42/backup.$NOW.tar.gz file, please wait..."
# rest of the script ...
# tar xcvf /nas42/backup.$NOW.tar.gz /home/ /etc/ /var
#...
#..

A complete list of FORMAT control characters supported by the GNU/date command

It can be the combination of any one of the following:

%FORMAT StringDescription
%%a literal %
%alocale’s abbreviated weekday name (e.g., Sun)
%Alocale’s full weekday name (e.g., Sunday)
%blocale’s abbreviated month name (e.g., Jan)
%Blocale’s full month name (e.g., January)
%clocale’s date and time (e.g., Thu Mar 3 23:05:25 2005)
%Ccentury; like %Y, except omit last two digits (e.g., 21)
%dday of month (e.g, 01)
%Ddate; same as %m/%d/%y
%eday of month, space padded; same as %_d
%Ffull date; same as %Y-%m-%d
%glast two digits of year of ISO week number (see %G)
%Gyear of ISO week number (see %V); normally useful only with %V
%hsame as %b
%Hhour (00..23)
%Ihour (01..12)
%jday of year (001..366)
%khour ( 0..23)
%lhour ( 1..12)
%mmonth (01..12)
%Mminute (00..59)
%na newline
%Nnanoseconds (000000000..999999999)
%plocale’s equivalent of either AM or PM; blank if not known
%Plike %p, but lower case
%rlocale’s 12-hour clock time (e.g., 11:11:04 PM)
%R24-hour hour and minute; same as %H:%M
%sseconds since 1970-01-01 00:00:00 UTC
%Ssecond (00..60)
%ta tab
%Ttime; same as %H:%M:%S
%uday of week (1..7); 1 is Monday
%Uweek number of year, with Sunday as first day of week (00..53)
%VISO week number, with Monday as first day of week (01..53)
%wday of week (0..6); 0 is Sunday
%Wweek number of year, with Monday as first day of week (00..53)
%xlocale’s date representation (e.g., 12/31/99)
%Xlocale’s time representation (e.g., 23:13:48)
%ylast two digits of year (00..99)
%Yyear
%z+hhmm numeric timezone (e.g., -0400)
%:z+hh:mm numeric timezone (e.g., -04:00)
%::z+hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::znumeric time zone with : to necessary precision (e.g., -04, +05:30)
%Zalphabetic time zone abbreviation (e.g., EDT)

A complete list of FORMAT control characters supported by the BSD/date command

The following works on Apple macOS/OS X, FreeBSD and *BSD version of the date command:

%FORMAT StringDescription
%Ais replaced by national representation of the full weekday name.
%ais replaced by national representation of the abbreviated weekday name.
%Bis replaced by national representation of the full month name.
%bis replaced by national representation of the abbreviated month name.
%Cis replaced by (year / 100) as decimal number; single digits are preceded by a zero.
%cis replaced by national representation of time and date.
%Dis equivalent to “%m/%d/%y”.
%dis replaced by the day of the month as a decimal number (01-31).
%E* %O*POSIX locale extensions. The sequences %Ec %EC %Ex %EX %Ey %EY %Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to provide alternate representations.
Additionally %OB implemented to represent alternative months names (used standalone, without day mentioned).
%eis replaced by the day of the month as a decimal number (1-31); single digits are preceded by a blank.
%Gis replaced by a year as a decimal number with century. This year is the one that contains the greater part of the week (Monday as the first day of the week).
%gis replaced by the same year as in “%G”, but as a decimal number without century (00-99).
%His replaced by the hour (24-hour clock) as a decimal number (00-23).
%hthe same as %b.
%Iis replaced by the hour (12-hour clock) as a decimal number (01-12).
%jis replaced by the day of the year as a decimal number (001-366).
%kis replaced by the hour (24-hour clock) as a decimal number (0-23); single digits are preceded by a blank.
%lis replaced by the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank.
%Mis replaced by the minute as a decimal number (00-59).
%mis replaced by the month as a decimal number (01-12).
%nis replaced by a newline.
%O*the same as %E*.
%pis replaced by national representation of either “ante meridiem” (a.m.) or “post meridiem” (p.m.) as appropriate.
%Ris equivalent to “%H:%M”.
%ris equivalent to “%I:%M:%S %p”.
%Sis replaced by the second as a decimal number (00-60).
%sis replaced by the number of seconds since the Epoch, UTC (see mktime(3)).
%Tis equivalent to “%H:%M:%S”.
%tis replaced by a tab.
%Uis replaced by the week number of the year (Sunday as the first day of the week) as a decimal number (00-53).
%uis replaced by the weekday (Monday as the first day of the week) as a decimal number (1-7).
%Vis replaced by the week number of the year (Monday as the first day of the week) as a decimal number (01-53). If the week containing January 1 has four or more days in the new year, then it is week 1; otherwise it is the last week of the previous year, and the next week is week 1.
%vis equivalent to “%e-%b-%Y”.
%Wis replaced by the week number of the year (Monday as the first day of the week) as a decimal number (00-53).
%wis replaced by the weekday (Sunday as the first day of the week) as a decimal number (0-6).
%Xis replaced by national representation of the time.
%xis replaced by national representation of the date.
%Yis replaced by the year with century as a decimal number.
%yis replaced by the year without century as a decimal number (00-99).
%Zis replaced by the time zone name.
%zis replaced by the time zone offset from UTC; a leading plus sign stands for east of UTC, a minus sign for west of UTC, hours and minutes follow with two digits each and no delimiter between them (common form for RFC 822 date headers).
%+is replaced by national representation of the date and time (the format is similar to that produced by date(1)).
%-*GNU libc extension. Do not do any padding when performing numerical outputs.
%_*GNU libc extension. Explicitly specify space for padding.
%0*GNU libc extension. Explicitly specify zero for padding.
%%is replaced by %.

A sample date session

I am running commands on macOS/OS X and FreeBSD:

date
date +"%T"
date +"%D"
date +"%m-%d-Y"
date "+%Y%m%d%H%M.%S"

Fig.01: date command in action

Fig.01: date command in action

Format given date

Say you want to print “April 23, 1978” as dd/mm/yyyy:
$ date -d "April 23, 1978" +"%d/%m/%Y"
Here is syntax for macOS or BSD/date command to print “April 23, 1978” as dd/mm/yyyy:
$ date -j -f "%INPUT_FORMAT" date_string +"%OUTPUT_FORMAT"
$ date -j -f "%Y%m%d" 19780423 +"%d/%m/%Y"

Let us print the following date in YYYY/mm/dd format in EDT timezone:
$ TZ="EDT" date -d "April 23, 2078 5:15:10 PM EDT" +"%Y/%m/%d"
The TZ shell variable determine the timezone in which the time and date are written. For example:
$ TZ='TIMZ_ZONE_HERE'
$ TZ='TIMZ_ZONE_HERE' date ...
$ TZ="IST" date # Indian Standard Time
$ TZ="EST" date # Eastern Time (ET)
$ TZ='Australia/Melbourne' date # AEDT

On Linux you can list all timezone using the ls command or tzselect command. For instance:
$ ls /usr/share/zoneinfo/

Africa      Arctic    Australia  CET      Cuba   Eire     Etc      GB       GMT+0  Greenwich  Iceland  iso3166.tab  Japan        leap-seconds.list  MET     MST7MDT  NZ-CHAT  Portugal    PRC      ROC        SystemV    UCT        UTC   zone1970.tab
America     Asia      Brazil     Chile    EET    EST      Europe   GB-Eire  GMT-0  Hongkong   Indian   Israel       Kwajalein    Libya              Mexico  Navajo   Pacific  posix       PST8PDT  ROK        Turkey     Universal  WET   zone.tab
Antarctica  Atlantic  Canada     CST6CDT  Egypt  EST5EDT  Factory  GMT      GMT0   HST        Iran     Jamaica      leapseconds  localtime          MST     NZ       Poland   posixrules  right    Singapore  tzdata.zi  US         W-SU  Zulu

Passing the --debug on GNU/date

We can annotate the parsed date, and warn about questionable usage to screen. For example:
$ date --debug -d "April 23, 1978" +"%d/%m/%Y"
Outputs:

date: parsed date part: (Y-M-D) 1978-04-23
date: input timezone: system default
date: warning: using midnight as starting time: 00:00:00
date: starting date/time: '(Y-M-D) 1978-04-23 00:00:00'
date: '(Y-M-D) 1978-04-23 00:00:00' = 262117800 epoch-seconds
date: timezone: system default
date: final: 262117800.000000000 (epoch-seconds)
date: final: (Y-M-D) 1978-04-22 18:30:00 (UTC)
date: final: (Y-M-D) 1978-04-23 00:00:00 (UTC+05:30)
23/04/1978

How to set TZ permanently

Say you want your TZ shell variable set to Africa/Algiers time zone, then you can make this change permanent for yourself by appending the line to the .profile or ~/.bash_profile file. in your home directory and then log out and log in again. For example:

TZ='Africa/Algiers'; export TZ

Chris

Chris

Just me, need more info?

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x