How To Format Date For Display or Use In a Shell Script

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.

ADVERTISEMENTS

Linux Syntax To Format Date For Display On Screen

Tutorial details
Difficulty Easy (rss)
Root privileges No
Requirements date
Time 5m
The syntax is as follows for the GNU/date and BSD/date command:
date +FORMAT
date +"%FORMAT"
date +"%FORMAT%FORMAT"
date +"%FORMAT-%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:
$ NOW=$(date +"%m-%d-%Y")
To display a variable use echo / printf command:
$ echo $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 script
# tar xcvf /nas42/backup.$NOW.tar.gz /home/ /etc/ /var

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

FORMAT controls the output. It can be the combination of any one of the following:

%FORMAT String Description
%% a literal %
%a locale’s abbreviated weekday name (e.g., Sun)
%A locale’s full weekday name (e.g., Sunday)
%b locale’s abbreviated month name (e.g., Jan)
%B locale’s full month name (e.g., January)
%c locale’s date and time (e.g., Thu Mar 3 23:05:25 2005)
%C century; like %Y, except omit last two digits (e.g., 21)
%d day of month (e.g, 01)
%D date; same as %m/%d/%y
%e day of month, space padded; same as %_d
%F full date; same as %Y-%m-%d
%g last two digits of year of ISO week number (see %G)
%G year of ISO week number (see %V); normally useful only with %V
%h same as %b
%H hour (00..23)
%I hour (01..12)
%j day of year (001..366)
%k hour ( 0..23)
%l hour ( 1..12)
%m month (01..12)
%M minute (00..59)
%n a newline
%N nanoseconds (000000000..999999999)
%p locale’s equivalent of either AM or PM; blank if not known
%P like %p, but lower case
%r locale’s 12-hour clock time (e.g., 11:11:04 PM)
%R 24-hour hour and minute; same as %H:%M
%s seconds since 1970-01-01 00:00:00 UTC
%S second (00..60)
%t a tab
%T time; same as %H:%M:%S
%u day of week (1..7); 1 is Monday
%U week number of year, with Sunday as first day of week (00..53)
%V ISO week number, with Monday as first day of week (01..53)
%w day of week (0..6); 0 is Sunday
%W week number of year, with Monday as first day of week (00..53)
%x locale’s date representation (e.g., 12/31/99)
%X locale’s time representation (e.g., 23:13:48)
%y last two digits of year (00..99)
%Y year
%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)
%:::z numeric time zone with : to necessary precision (e.g., -04, +05:30)
%Z alphabetic time zone abbreviation (e.g., EDT)

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

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

%A is replaced by national representation of the full weekday name.
%a is replaced by national representation of the abbreviated weekday name.
%B is replaced by national representation of the full month name.
%b is replaced by national representation of the abbreviated month name.
%C is replaced by (year / 100) as decimal number; single digits are preceded by a zero.
%c is replaced by national representation of time and date.
%D is equivalent to “%m/%d/%y”.
%d is 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).
%e is replaced by the day of the month as a decimal number (1-31); single digits are preceded by a blank.
%G is 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).
%g is replaced by the same year as in “%G”, but as a decimal number without century (00-99).
%H is replaced by the hour (24-hour clock) as a decimal number (00-23).
%h the same as %b.
%I is replaced by the hour (12-hour clock) as a decimal number (01-12).
%j is replaced by the day of the year as a decimal number (001-366).
%k is replaced by the hour (24-hour clock) as a decimal number (0-23); single digits are preceded by a blank.
%l is replaced by the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank.
%M is replaced by the minute as a decimal number (00-59).
%m is replaced by the month as a decimal number (01-12).
%n is replaced by a newline.
%O* the same as %E*.
%p is replaced by national representation of either “ante meridiem” (a.m.) or “post meridiem” (p.m.) as appropriate.
%R is equivalent to “%H:%M”.
%r is equivalent to “%I:%M:%S %p”.
%S is replaced by the second as a decimal number (00-60).
%s is replaced by the number of seconds since the Epoch, UTC (see mktime(3)).
%T is equivalent to “%H:%M:%S”.
%t is replaced by a tab.
%U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number (00-53).
%u is replaced by the weekday (Monday as the first day of the week) as a decimal number (1-7).
%V is 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.
%v is equivalent to “%e-%b-%Y”.
%W is replaced by the week number of the year (Monday as the first day of the week) as a decimal number (00-53).
%w is replaced by the weekday (Sunday as the first day of the week) as a decimal number (0-6).
%X is replaced by national representation of the time.
%x is replaced by national representation of the date.
%Y is replaced by the year with century as a decimal number.
%y is replaced by the year without century as a decimal number (00-99).
%Z is replaced by the time zone name.
%z is 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

Fig.01: date command in action

Fig.01: date command in action

Conclusion

This page showed how to format dates on Linux and Unix like systems. For more information see the following pages:

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
66 comments… add one
  • Michael Shuler Feb 27, 2007 @ 22:38

    An alternate that I use for several scripts is to eval $TIME and add useful text – uses similar format statements as date – see the manpage.

    19453460845f954bfea41ee_000001

    Outputs:

    alpha.nyc elapsed time: 0:30.82
    beta.lax elapsed time: 1:01.81
    gamma.lon elapsed time: 2:39.64
  • noel villeroz Mar 22, 2007 @ 21:07

    It’s great and I learned a lot from this topic…

  • neo424 Jul 13, 2007 @ 7:53

    I need to send my analog hits to my email box automatically.

    This is my command set,

    cd /home/cpanelaccount/tmp/analog
    ls -al
    grep id=55 4.html | wc -l | mail -s “csppg hits” my@emailc.om

    analog create log files 1-12.htm. ex: 4.html for April. After year it replace these files.

    How do I determent the month and make my commands automatic send information using cronjob?

  • unique Nov 12, 2007 @ 4:49

    how can get week of the month?..
    ex : 1102 (second week in the november)

  • vij Jan 11, 2008 @ 12:38

    how do i comapre time in 07:35:15AM format through shell script

    • Harjeet Kaur Aug 16, 2015 @ 22:29

      19453460845f954bfea41ee_000002

  • Dravid May 29, 2009 @ 10:55

    Nice one.

  • comrad Jun 17, 2009 @ 9:21

    Oh nice :-) And available via IPv6!

  • ashwani Jun 18, 2009 @ 10:43

    for space we can use \
    see the output
    Work Hard buddy [root@server1 04:05 PM]\ date +%F\ %r
    2009-06-18 04:05:45 PM

  • Mangesh Oct 9, 2009 @ 7:30

    How to display yesterday date?

  • Me Oct 30, 2009 @ 7:52

    Thanks a BUNCH !
    That was simple and effective for the beginners.

  • Miroslav Mar 2, 2010 @ 14:56

    I setup linux script to delete my backups older than few days:
    RBRDAN=`date –date=”3 days ago” +%w`

    rm /u02/oracle/backup/rman/$RBRDAN/*

    But, I got error:
    rm: cannot remove `/u02/oracle/backup/rman/6\r/*’: No such file or directory

    For some reason, it gives me “\r” at the end of the day. Instead of “6”, it gives me “6\r”.
    Does anybody know what is the problem.

    Thanks.

  • Guy Mar 24, 2010 @ 20:41

    Hi everyone!
    This is a great document that covers most of my date/time issues :-)

    However I am trying to cron a job that will execute my bash script, the challenge that I am facing is I need to run the script for the last 12 hours, here is what I have:

    #!/usr/bin/bash
    # Set the current local time in this format: ’03/18/2010 17:52:18′
    CURR_DATE=`date +%m/%d/%Y” “%H:%M:%S`
    #Set the start time (current time – 12 hours) <– This is where I am stuck!!!
    START_DATE=`date +%m/%d/%Y" "%T`

    How do set the start time to CURR_DATE -12 hours???

    Thanks,
    guy

  • Guy Mar 24, 2010 @ 20:51

    I should mentioned that I am using SunOS 5.10
    As I have tried
    E=$(date –date=’-12 hours’)
    and it’s not working!

    I get this error:
    date: illegal option — date=-12 hours
    usage: date [-u] mmddHHMM[[cc]yy][.SS]
    date [-u] [+format]
    date -a [-]sss[.fff]

  • Guy Mar 24, 2010 @ 21:57

    So I got this from a friend, how recommended to use perl:

    CURR_DATE=`perl -e ‘use POSIX qw(strftime);$d = strftime “%m/%e/%Y %H:%M:%S”, localtime(time);print $d;’`
    START_DATE=` perl -e ‘use POSIX qw(strftime);$d = strftime “%m/%e/%Y %H:%M:%S”, localtime(time() – 43200);print $d;’`
    echo $CURR_DATE
    echo $START_DATE

    This works great!!

  • Balaswamy vaddeman Aug 28, 2010 @ 9:18

    it is good one for unix beginners.
    I want to display month in aphabets like Jan ,Feb and Mar.
    anybody suggest me command for that. thank you in advance.

    • 🐧 nixCraft Aug 28, 2010 @ 9:26

      Tested with GNU date:

      date +"%b" 
      date +"%b" --date="1 month ago"
      for d in {1..6}; do date +"%b" --date="$d month ago"; done
      man date
  • bhavesh Sep 13, 2010 @ 23:42

    @Balaswamy : easiest way to print months in alphabets format is using CASE

  • Balaswamy vaddeman Sep 22, 2010 @ 5:19

    Thank you Bhavesh ,%b option also worked for me.

  • Amit Jain Dec 15, 2010 @ 6:48

    Thanks a lot it helped.

  • saianth chemate Mar 5, 2011 @ 5:56

    hellow…..
    I was thinking for writing code for the date formate comperison
    if any one having any idea abt it plz informe me…….
    i willl apriciate that…

  • soumita Jun 3, 2011 @ 7:30

    Hi,

    I am writing a script which needs 2 arguments – arg1: current date & time,arg2: 5 min after date & time.Can anyone help me how to get after 5 min time of current time in sun 5.10?I have tried with the below syntax, but it is not working.

    a=`date “+%Y%m%d %T” -d “+5 min”`

    • Ashish Jul 7, 2013 @ 12:17

      a= date “+%Y%m%d%T” -d +5 min”

  • phpsnook Jul 8, 2011 @ 7:25

    Hi i have a unix date in file a file like this ‘1313675999’
    in oracle i would do it like this

    select TO_CHAR ( TO_DATE (‘01011970’, ‘DDMMYYYY’)+ 1 / 24 / 60 / 60 * 1313675999,’YYYYMMDD’) from dual

    how to achive the same in unix ?

    • phpsnook Jul 8, 2011 @ 11:44

      echo 1313675999 | perl -e ‘use Time::localtime; $tm=localtime(); printf(“%d/%d/%d\n”, $tm->mday, $tm->mon+1, $tm->year+1900);’

  • Another Guy Aug 23, 2011 @ 19:29

    How do I get the day of the week for tomorrow and the day after? For example, if today is Monday, how can I get “Tuesday” and “Wednesday”? I have weather data for day2 and day3 from getwthr.com (for GeekTool) but need the days of the week to apply it to.

    Thanks.

  • Lernen Jan 4, 2012 @ 7:34

    Thank you!! I tried to format a date string for myself but date –help didnt show anything about the “+” which is important for formating…. -.- thanks again!

  • bala Jun 19, 2012 @ 14:03

    Thanks a lot… it really helped me..

  • Sathish Sundaravel Aug 31, 2012 @ 6:36

    How do i print the yesterday date

  • aleci Oct 3, 2012 @ 14:18

    Hi guys! This site is really informative but I have one question. Given a specific date entered by the user how can I pass that for the date function to format and display?

    Thanks!

  • Cr0t Feb 27, 2013 @ 21:50

    that so didn’t work for me…. I wrote a dirty work around

    my variable ALLDATES looks like this
    02/11/13
    02/12/13
    02/13/13
    02/14/13
    02/15/13

    —BEGIN—
    for sorttime in $ALLDATES;
    do
    date +%s -d “$sorttime” >> $$
    done

    ALLDATES=`cat $$ | sort`
    rm $$ -f

    for sorttime in $ALLDATES;
    do
    date -d @$sorttime +%D >> $$
    done

    ALLDATES=`cat $$`
    rm $$ -f
    —END—

    Yeah…. this is not pretty, but it does the jobs. It converts the time into ctime, sorts it and then puts it back.

  • danmark Jun 20, 2013 @ 14:44

    great help for this noob.
    works for
    dehdate=$(date +%Y%m%d”)
    dehdmsg1=”HELLO $dehdate”
    echo dehdmsg1
    .
    does not work for
    dehdmsg2 =”$dehdate HELLO”
    echo dehdmsg2
    yields
    HELLO20
    Will do more looking.

  • Rick Carrick Jul 12, 2013 @ 20:32

    date +%c –date=”tomorrow”

  • Tsunami Australia Sep 2, 2013 @ 10:26

    Thanks a heap for this document. I was looking for a method of naming cron’ed backup files on a CentOS webserver so could have backup-*date*-etc, backup-*date*-var_www etc

    Using the methods you’ve shown I will be able to automate this backup process using a bash script and cron then just log in via VPN and download the backup files via SAMBA once a week.

  • Krishanu May 21, 2014 @ 20:32

    I need to move a date file ( for ex, 22-05-2014.csv) from one folder to another folder in Unix. But the problem is that the file must be dynamic ( for ex, if I have to transfer the file today, the transferred file should look like 22052014.csv, if I transfer it tomorrow, it should look like 23052014.csv and so on).

    I have the basic idea that I have to move the file date +”%d%m%Y”.csv to my destination folder. But not able to do it. Or rather, I do not know how to do it. Please help.

  • comrad May 22, 2014 @ 4:28

    You have to put the date-command in backticks or $(command).

    Then bash executes the command and uses the result to continue.

  • Srikanth May 27, 2014 @ 4:56

    I got what I wanted. Thank you

  • kokane Nov 19, 2014 @ 9:49

    Great script!

  • notaposter Mar 13, 2015 @ 21:51
     NOW=$(date +"%m-%d-%Y")

    does not work in Ubuntu

    • jack Mar 15, 2015 @ 10:34

      it does work Ubuntu 14.04 LTS. Beside that all distributions got the same binutils….

  • marcus Mar 17, 2015 @ 10:53

    I want to set a start-date to 2014-01-01
    and then go through the whole year but I can’t figure out how to set the start-date to a specific date. someone kind enough to help? :)

  • Prasanna Mar 26, 2015 @ 9:33

    Can anyone help me get a script to calculate number of months since a date till current date? Ex: No of months till today from July 2013

  • DJ Apr 16, 2015 @ 9:18

    I have one variable “ym” such as YearMOnth (201503). I want to reduce it to one month when i pass this parameter through some function and get output as “201502”.

    Can you help me in that

  • Aeternum Sep 18, 2015 @ 17:36

    I have this variables

    DATE_OP=`date +%Y-%m-%d`
    DATE3_1=$(date --date "-3 year -1 day" +%Y-%m-%d)

    DATE3_1 returns me the current date minus 3 years and 1 day, but I need to get that date range with a parameter in specific, not the sysdate.

    Something like:

    DATE=$1
    DATE3_1=$($DATE --date "-3 year -1 day" +%Y-%m-%d)

    But I don’t get it.

  • Dave Jin Mar 31, 2016 @ 4:15

    How can I get the month ‘3’ not ’03’ for march using %m.

    • 🐧 Vivek Gite Mar 31, 2016 @ 5:01

      You can’t. But, you can use sed to remove 0.
      m=$(date +'%m' | sed 's/0//')
      echo $m
      3

  • john Mar 31, 2016 @ 17:02

    fyi the echo in your sample is superfluous instead of

    echo "Timezine $(date +'%Z')"

    you can do

    date +'Timezone: %Z'

  • koodalingam Apr 7, 2016 @ 16:31

    I got what I expected.. nice …..

  • abhishek Apr 15, 2016 @ 9:03

    whenever i give the command 00 18 * * * for backup in crontabs it is showing 00: command not found.
    May i know why???

  • DodoGTA GT Jun 25, 2016 @ 9:22

    I recently used this date format:
    yyyymmdd
    With this command:
    date +%Y%m%d
    Here’s an example:
    20160625 // Date I’m writing this

  • Girish Jul 7, 2016 @ 4:27

    I am storing date in variable on sun solaris os.

    a= “Sun Jul 3 18:05:23 CEST 2016”

    Want to format this output to : 03-07-2016 18:05:23

    In linux os this can be done using -d but on sun solaris -d option is not available. Any solution ?

    Thanks
    Girish

  • Srini Aug 30, 2016 @ 16:12

    Thanks a lot for the steps. I appreciate. Great job.

  • hiddenotebok Aug 31, 2016 @ 15:33

    I have come here through google looking for exactly what you explain here! nice job thank you.
    I’m trying to pipe this to festival and make and script, you can try this:
    date +"The time is %X Today is %A" | festival --tts
    but festival spell out the day, anyone know how I can make it say the day well?

    • hiddenotebook Sep 10, 2016 @ 23:43

      Y made it he he
      date "+%H:%M %P %A %d %B %Y"| festival --tts
      with a hot and nice voice Alice…
      sudo apt-get install festival

      Make a directory to do the job:

      mkdir myvoice
      cd myvoice

      Download this great and clear voice:

      wget http://www.speech.cs.cmu.edu/cmu_arctic/packed/cmu_us_slt_arctic-0.95-release.tar.bz2
      Extract it:

      tar xf cmu_us_slt_arctic-0.95-release.tar.bz2

      Now move it to festival. Beware, we need to change the name here add _clunits suffix ok:

      sudo mv cmu_us_slt_arctic /usr/share/festival/voices/english/cmu_us_slt_arctic_clunits

      Make it the default voice : edit festival config file add this to a new line (/etc/festival*.scm)

      (set! voice_default 'voice_cmu_us_slt_arctic_clunits)

      Now start festival:

      festival

      Test it:

      (SayText "Hello I am Alice. hot and nice. This is a short introduction test.")

      Your Welcome.

  • Nani Sep 21, 2016 @ 14:45

    I have date like this Jan 20, 2016 11:58:09 AM EST . i need to convert this to 2016-01-20 11:58:09

  • Preet Oct 3, 2016 @ 14:12

    Its very help full, How can I get the abbreviated month like
    date +%b will give “Oct” but I need the output as “OCT” – All upper case.

    Can you please help?

    • 🐧 Vivek Gite Oct 5, 2016 @ 21:32

      date +"%b" | tr 'a-z' 'A-Z'

      • Preet Oct 6, 2016 @ 11:50

        Classic!!.. Thanks a lot Vivek.. :)

  • Chennakesava C Aug 12, 2020 @ 5:16

    I have tried with
    stat -c %y last_generated_2020.08.12-09.06.40.txt
    and the output be like

    2020-08-12 09:06:40.642728361 +0530

    How to get only the date and time as below
    2020-08-12 09:06:40

    • 🐧 Vivek Gite Aug 12, 2020 @ 11:38

      Try:

      19453460845f954bfea41ee_000003

      You can use awk or perl or python too.

  • Yatin Sep 5, 2020 @ 10:31

    my logs are in format

    %Y%m%d%H%M.log

    so I want add a script in which I would put the desire value for log time and at the same time my script should search for previous day logs

    example:
    ./error.sh 202009051314
    so my script should search for logs
    202009051314.log & 202009041314.log

    Any suggestion?

  • Heriberto Martinez Oct 15, 2020 @ 2:04

    This page is awesome!

    Keep the good work.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.