Softpanorama

Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
May the source be with you, but remember the KISS principle ;-)
Skepticism and critical thinking is not panacea, but can help to understand the world better

date command

News Recommended Books Recommended Links Configuring Time Services in RHEL 7 Configuring network in RHEL7 Reference

Examples

RHEL 6 NTP configuration Troubleshooting NTP on Red Hat Linux Troubleshooting NTP on Solaris Configuring a Solaris NTP Server Changing timezone in RHEL6 from the command line    
Find Command Webliography tar Admin Horror Stories Unix History Touch command Humor

Etc


Introduction

Command date is implemented as a binary (usually /bin/date). It is a very powerful utility with several modes of operation, including data calculator mode and referenced file mode. It also can set the time. The most typical usage is to create a timestamp is user-defined format, specified in a special format string with more then two dozen of built-in macros (format strings). The most common macros in format string are:

BSD version and GNU version has the ability to convert date representation in seconds to any format you wish.  There are also numerous "Unix timestamp calculators" on the WEB. For example

Command date was first seen in Version 1 of AT&T Unix, circa 1969, and has both grown and improved over the years to provide you with a wide variety of configurable options for your system. 

Creating timestamp

The most important for scripting functionality of date is the the ability to create timestamp is wide variety of formats.

date +"%Y/%m/%d %H:%M"

The output should look something like this:

2010/01/04 06:28

The format string %Y/%m/%d %H:%M is called date conversion template and it consist of individual single letter macros prefixed with % sign (here they are %Y,%m,%d,%H  and %M) and "filler" text. Please note that if you date conversion template contains spaces you need to put it in single or double quotes, for example

date +"%Y/%m/%d %H:%M"

is correct and

date +%Y/%m/%d %H:%M

is not.

If  you are OK with two year year representation you can use %y instead of %Y. There is also a macro %D that provides date in  mm/dd/yy format, so we can rewrite the previous example as

     date +"%D %H:%M"

Please note that if your date conversion template contains spaces you need to put it in single or double quotes

Using date as date calculator (option -d)

Option -d provides the opportunity to use data as a simple data calculator

date -d yesterday +"%y%m%d" 
date -d tomorrow +"%y%m%d"

The -d option which has long format --date=STRING is a free format human readable date string such as

A date string may contain items indicating calendar date, time of day, time zone, day of week, relative time, relative date, and numbers. An empty string indicates the beginning of the day. 

For example (GNU date only):
date +"%Y%m%d" -d sunday # GNU date
20060709

date +"%Y%m%d" -d last-sunday # GNU date
20060702

date +"%Y%m%d" -d last-week # GNU date
date -v -1m +"%Y%m%d" # BSD date
20060627

date +"%Y%m%d" -d last-month # GNU date
date -v -1w +"%Y%m%d" # BSD date
20060604

date +"%Y%m%d" -d last-year # GNU date
date -v -1y +"%Y%m%d" # BSD date
20050704

date +"%Y%m%d" -d next-week # GNU date
date -v 1w +"%Y%m%d" # BSD date
20060711

date +"%Y%m%d" -d next-month # GNU date
date -v 1m +"%Y%m%d" # BSD date
20060804

date +"%Y%m%d" -d next-year # GNU date
date -v 1y +"%Y%m%d" # BSD date
20070704

To show the time in seconds since 1970-01-01 (Unix epoch):

date +"%s" -d "Fri Apr 24 13:14:39 CDT 2009"
1240596879

To convert Unix epoch time (seconds since 1970-01-01) to a human readable format:

date -d "UTC 1970-01-01 1240596879 secs"
Fri Apr 24 13:14:39 CDT 2009

Or:

date -ud @1000000000
Sun Sep  9 01:46:40 UTC 2001

Using date for offset calculation:

date +"%Y%m%d" -d sunday
20060709

date +"%Y%m%d" -d last-sunday
20060702

date +"%Y%m%d" -d last-week
20060627

date +"%Y%m%d" -d last-month
20060604

date +"%Y%m%d" -d last-year
20050704

date +"%Y%m%d" -d next-week
20060711

date +"%Y%m%d" -d next-month
20060804

date +"%Y%m%d" -d next-year
20070704

 

Using the date of referenced file instead of now

Date also can work not with the current time, but with time of modification of the referenced file

date -r /etc/passwd +"%y%m%d"

You can convert time to a new format, for example second since Unix epoch using option -d

timestamp="Feb 19 17:01" 
reboot_time=`date -d "$timestamp" +%s`

It also can serve as data calculator.

Most important build-in macros

Here  are most important build-in macros:

 

Examples

date "+%-m/%-d/%y" 
7/4/06
date "+%Y%m%d"
20060704

date  +"%b %d, %Y"
Mar 14, 2010

date -d yesterday +"%Y/%m/%d"
2010/03/13

Yesterday assigned to variable

DATE=$(date -d yesterday +"%Y%m%d")
echo $DATE
20060704

To assign the time to a variable

START=`date '+%r'`
echo $START
03:06:02 PM
sleep 5
echo $START
03:06:02 PM

To show the time in a different timezone, the TZ environment variable is read, Timezone types is found in /usr/share/zoneinfo

OLDTZ=$TZ
export TZ=GMT; echo "GMT:               `date +\"%F %R (%Z)\"`"
GMT:               2008-10-31 12:30 (GMT)
export TZ=Europe/Stockholm; echo "Stockholm:    `date +\"%F %R (%Z)\"`"
Stockholm:    2008-10-31 13:30 (CET)
export TZ=Asia/Kuala_Lumpur; echo "Kuala Lumpur: `date +\"%F %R (%Z)\"`"
Kuala Lumpur:        2008-10-31 20:30 (MYT)
export TZ=US/Central; echo "Dallas:             `date +\"%F %R (%Z)\"`"
Dallas:             2008-10-31 07:30 (CDT)
export TZ=$OLDTZ

Using date for offset calculation:

date +"%Y%m%d" -d sunday
20060709

date +"%Y%m%d" -d last-sunday
20060702

date +"%Y%m%d" -d last-week
20060627

date +"%Y%m%d" -d last-month
20060604

date +"%Y%m%d" -d last-year
20050704

date +"%Y%m%d" -d next-week
20060711

date +"%Y%m%d" -d next-month
20060804

date +"%Y%m%d" -d next-year
20070704

Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

[Mar 04, 2020] A command-line HTML pretty-printer Making messy HTML readable - Stack Overflow

Jan 01, 2019 | stackoverflow.com

A command-line HTML pretty-printer: Making messy HTML readable [closed] Ask Question Asked 10 years, 1 month ago Active 10 months ago Viewed 51k times


knorv ,

Closed. This question is off-topic . It is not currently accepting answers.

jonjbar ,

Have a look at the HTML Tidy Project: http://www.html-tidy.org/

The granddaddy of HTML tools, with support for modern standards.

There used to be a fork called tidy-html5 which since became the official thing. Here is its GitHub repository .

Tidy is a console application for Mac OS X, Linux, Windows, UNIX, and more. It corrects and cleans up HTML and XML documents by fixing markup errors and upgrading legacy code to modern standards.

For your needs, here is the command line to call Tidy:

tidy inputfile.html

Paul Brit ,

Update 2018: The homebrew/dupes is now deprecated, tidy-html5 may be directly installed.
brew install tidy-html5

Original reply:

Tidy from OS X doesn't support HTML5 . But there is experimental branch on Github which does.

To get it:

 brew tap homebrew/dupes
 brew install tidy --HEAD
 brew untap homebrew/dupes

That's it! Have fun!

Boris , 2019-11-16 01:27:35

Error: No available formula with the name "tidy" . brew install tidy-html5 works. – Pysis Apr 4 '17 at 13:34

[Feb 28, 2020] linux - Convert a time span in seconds to formatted time in shell - Stack Overflow

Jan 01, 2012 | stackoverflow.com

Convert a time span in seconds to formatted time in shell Ask Question Asked 7 years, 3 months ago Active 2 years ago Viewed 43k times


Darren , 2012-11-16 18:59:53

I have a variable of $i which is seconds in a shell script, and I am trying to convert it to 24 HOUR HH:MM:SS. Is this possible in shell?

sampson-chen , 2012-11-16 19:17:51

Here's a fun hacky way to do exactly what you are looking for =)
date -u -d @${i} +"%T"

Explanation:

glenn jackman ,

Another approach: arithmetic
i=6789
((sec=i%60, i/=60, min=i%60, hrs=i/60))
timestamp=$(printf "%d:%02d:%02d" $hrs $min $sec)
echo $timestamp

produces 1:53:09

Alan Tam , 2014-02-17 06:48:21

The -d argument applies to date from coreutils (Linux) only.

In BSD/OS X, use

date -u -r $i +%T

kossboss , 2015-01-07 13:43:36

Here is my algo/script helpers on my site: http://ram.kossboss.com/seconds-to-split-time-convert/ I used this elogant algo from here: Convert seconds to hours, minutes, seconds
convertsecs() {
 ((h=${1}/3600))
 ((m=(${1}%3600)/60))
 ((s=${1}%60))
 printf "%02d:%02d:%02d\n" $h $m $s
}
TIME1="36"
TIME2="1036"
TIME3="91925"

echo $(convertsecs $TIME1)
echo $(convertsecs $TIME2)
echo $(convertsecs $TIME3)

Example of my second to day, hour, minute, second converter:

# convert seconds to day-hour:min:sec
convertsecs2dhms() {
 ((d=${1}/(60*60*24)))
 ((h=(${1}%(60*60*24))/(60*60)))
 ((m=(${1}%(60*60))/60))
 ((s=${1}%60))
 printf "%02d-%02d:%02d:%02d\n" $d $h $m $s
 # PRETTY OUTPUT: uncomment below printf and comment out above printf if you want prettier output
 # printf "%02dd %02dh %02dm %02ds\n" $d $h $m $s
}
# setting test variables: testing some constant variables & evaluated variables
TIME1="36"
TIME2="1036"
TIME3="91925"
# one way to output results
((TIME4=$TIME3*2)) # 183850
((TIME5=$TIME3*$TIME1)) # 3309300
((TIME6=100*86400+3*3600+40*60+31)) # 8653231 s = 100 days + 3 hours + 40 min + 31 sec
# outputting results: another way to show results (via echo & command substitution with         backticks)
echo $TIME1 - `convertsecs2dhms $TIME1`
echo $TIME2 - `convertsecs2dhms $TIME2`
echo $TIME3 - `convertsecs2dhms $TIME3`
echo $TIME4 - `convertsecs2dhms $TIME4`
echo $TIME5 - `convertsecs2dhms $TIME5`
echo $TIME6 - `convertsecs2dhms $TIME6`

# OUTPUT WOULD BE LIKE THIS (If none pretty printf used): 
# 36 - 00-00:00:36
# 1036 - 00-00:17:16
# 91925 - 01-01:32:05
# 183850 - 02-03:04:10
# 3309300 - 38-07:15:00
# 8653231 - 100-03:40:31
# OUTPUT WOULD BE LIKE THIS (If pretty printf used): 
# 36 - 00d 00h 00m 36s
# 1036 - 00d 00h 17m 16s
# 91925 - 01d 01h 32m 05s
# 183850 - 02d 03h 04m 10s
# 3309300 - 38d 07h 15m 00s
# 1000000000 - 11574d 01h 46m 40s

Basile Starynkevitch ,

If $i represents some date in second since the Epoch, you could display it with
  date -u -d @$i +%H:%M:%S

but you seems to suppose that $i is an interval (e.g. some duration) not a date, and then I don't understand what you want.

Shilv , 2016-11-24 09:18:57

I use C shell, like this:
#! /bin/csh -f

set begDate_r = `date +%s`
set endDate_r = `date +%s`

set secs = `echo "$endDate_r - $begDate_r" | bc`
set h = `echo $secs/3600 | bc`
set m = `echo "$secs/60 - 60*$h" | bc`
set s = `echo $secs%60 | bc`

echo "Formatted Time: $h HOUR(s) - $m MIN(s) - $s SEC(s)"
Continuing @Daren`s answer, just to be clear: If you want to use the conversion to your time zone , don't use the "u" switch , as in: date -d @$i +%T or in some cases date -d @"$i" +%T

[Dec 12, 2019] Use timedatectl to Control System Time and Date in Linux

Dec 12, 2019 | www.maketecheasier.com

Mastering the Command Line: Use timedatectl to Control System Time and Date in Linux By Himanshu Arora – Posted on Nov 11, 2014 Nov 9, 2014 in Linux

The timedatectl command in Linux allows you to query and change the system clock and its settings. It comes as part of systemd, a replacement for the sysvinit daemon used in the GNU/Linux and Unix systems.

In this article, we will discuss this command and the features it provides using relevant examples.

Timedatectl examples

Note – All examples described in this article are tested on GNU bash, version 4.3.11(1).

Display system date/time information

Simply run the command without any command line options or flags, and it gives you information on the system's current date and time, as well as time-related settings. For example, here is the output when I executed the command on my system:

$ timedatectl
      Local time: Sat 2014-11-08 05:46:40 IST
  Universal time: Sat 2014-11-08 00:16:40 UTC
        Timezone: Asia/Kolkata (IST, +0530)
     NTP enabled: yes
NTP synchronized: yes
 RTC in local TZ: no
      DST active: n/a

So you can see that the output contains information on LTC, UTC, and time zone, as well as settings related to NTP, RTC and DST for the localhost.

Update the system date or time using the set-time option

To set the system clock to a specified date or time, use the set-time option followed by a string containing the new date/time information. For example, to change the system time to 6:40 am, I used the following command:

$ sudo timedatectl set-time "2014-11-08 06:40:00"

and here is the output:

$ timedatectl
      Local time: Sat 2014-11-08 06:40:02 IST
  Universal time: Sat 2014-11-08 01:10:02 UTC
        Timezone: Asia/Kolkata (IST, +0530)
     NTP enabled: yes
NTP synchronized: no
 RTC in local TZ: no
      DST active: n/a

Observe that the Local time field now shows the updated time. Similarly, you can update the system date, too.

Update the system time zone using the set-timezone option

To set the system time zone to the specified value, you can use the set-timezone option followed by the time zone value. To help you with the task, the timedatectl command also provides another useful option. list-timezones provides you with a list of available time zones to choose from.

For example, here is the scrollable list of time zones the timedatectl command produced on my system:

timedatectl-timezones

To change the system's current time zone from Asia/Kolkata to Asia/Kathmandu, here is the command I used:

$ timedatectl set-timezone Asia/Kathmandu

and to verify the change, here is the output of the timedatectl command:

$ timedatectl
      Local time: Sat 2014-11-08 07:11:23 NPT
  Universal time: Sat 2014-11-08 01:26:23 UTC
        Timezone: Asia/Kathmandu (NPT, +0545)
     NTP enabled: yes
NTP synchronized: no
 RTC in local TZ: no
      DST active: n/a

You can see that the time zone was changed to the new value.

Configure RTC

You can also use the timedatectl command to configure RTC (real-time clock). For those who are unaware, RTC is a battery-powered computer clock that keeps track of the time even when the system is turned off. The timedatectl command offers a set-local-rtc option which can be used to maintain the RTC in either local time or universal time.

This option requires a boolean argument. If 0 is supplied, the system is configured to maintain the RTC in universal time:

$ timedatectl set-local-rtc 0

but in case 1 is supplied, it will maintain the RTC in local time instead.

$ timedatectl set-local-rtc 1

A word of caution : Maintaining the RTC in the local time zone is not fully supported and will create various problems with time zone changes and daylight saving adjustments. If at all possible, use RTC in UTC.

Another point worth noting is that if set-local-rtc is invoked and the --adjust-system-clock option is passed, the system clock is synchronized from the RTC again, taking the new setting into account. Otherwise the RTC is synchronized from the system clock.

Configure NTP-based network time synchronization

NTP, or Network Time Protocol, is a networking protocol for clock synchronization between computer systems over packet-switched, variable-latency data networks. It is intended to synchronize all participating computers to within a few milliseconds of UTC.

The timedatectl command provides a set-ntp option that controls whether NTP based network time synchronization is enabled. This option expects a boolean argument. To enable NTP-based time synchronization, run the following command:

$ timedatectl set-ntp true

To disable, run:

$ timedatectl set-ntp false
Conclusion

As evident from the examples described above, the timedatectl command is a handy tool for system administrators who can use it to to adjust various system clocks and RTC configurations as well as poll remote servers for time information. To learn more about the command, head over to its man page .

[Dec 12, 2019] Set Time-Date-Timezone using Command Line in Linux

Dec 12, 2019 | linoxide.com

Set Time/Date/Timezone in Ubuntu Linux February 5, 2019 Updated September 27, 2019 By Pungki Arianto LINUX COMMANDS , LINUX HOWTO How to set time and time zone in ubuntu linux

Time is an important aspect in Linux systems especially in critical services such as cron jobs. Having the correct time on the server ensures that the server operates in a healthy environment that consists of distributed systems and maintains accuracy in the workplace.

In this tutorial, we will focus on how to set time/date/time zone and to synchronize the server clock with your Ubuntu Linux machine.

Check Current Time

You can verify the current time and date using the date and the timedatectl commands. These linux commands can be executed straight from the terminal as a regular user or as a superuser. The commands are handy usefulness of the two commands is seen when you want to correct a wrong time from the command line.

Using the date command

Log in as a root user and use the command as follows

$ date

Output

check date using date command

You can also use the same command to check a date 2 days ago

$ date --date="2 days ago"

Output

check date 2 days ago

Using timedatectl command

Checking on the status of the time on your system as well as the present time settings, use the command timedatectl as shown

# timedatectl

or

# timedatectl  status

how to set time

Changing Time

We use the timedatectl to change system time using the format HH:MM: SS. HH stands for the hour in 24-hour format, MM stands for minutes and SS for seconds.

Setting the time to 09:08:07 use the command as follows (using the timedatectl)

# timedatectl set-time 09:08:07
using date command

Changing time means all the system processes are running on the same clock putting the desktop and server at the same time. From the command line, use date command as follows

# date +%T -s "10:13:13"

Where,
• 10: Hour (hh)
• 13: Minute (mm)
• 13: Second (ss)

To change the locale to either AM or PM use the %p in the following format.

# date +%T%p -s "6:10:30AM"
# date +%T%p -s "12:10:30PM"
Change Date

Generally, you want your system date and time is set automatically. If for some reason you have to change it manually using date command, we can use this command :

# date --set="20140125 09:17:00"

It will set your current date and time of your system into 'January 25, 2014' and '09:17:00 AM'. Please note, that you must have root privilege to do this.

You can use timedatectl to set the time and the date respectively. The accepted format is YYYY-MM-DD, YYYY represents the year, MM the month in two digits and DD for the day in two digits. Changing the date to 15 January 2019, you should use the following command

# timedatectl set-time 20190115
Create custom date format

To create custom date format, use a plus sign (+)

$ date +"Day : %d Month : %m Year : %Y"
Day: 05 Month: 12 Year: 2013

$ date +%D
12/05/13

%D format follows Year/Month/Day format .

You can also put the day name if you want. Here are some examples :

$ date +"%a %b %d %y"
Fri 06 Dec 2013

$ date +"%A %B %d %Y"
Friday December 06 2013

$ date +"%A %B %d %Y %T"
Friday December 06 2013 00:30:37

$ date +"%A %B-%d-%Y %c"
Friday December-06-2013 12:30:37 AM WIB

List/Change time zone

Changing the time zone is crucial when you want to ensure that everything synchronizes with the Network Time Protocol. The first thing to do is to list all the region's time zones using the list-time zones option or grep to make the command easy to understand

# timedatectl list-timezones

The above command will present a scrollable format.

list time zones

Recommended timezone for servers is UTC as it doesn't have daylight savings. If you know, the specific time zones set it using the name using the following command

# timedatectl set-timezone America/Los_Angeles

To display timezone execute

# timedatectl | grep "Time"

check timezone

Set the Local-rtc

The Real-time clock (RTC) which is also referred to as the hardware clock is independent of the operating system and continues to run even when the server is shut down.

Use the following command

# timedatectl set-local-rtc 0

In addition, the following command for the local time

# timedatectl set-local-rtc 1
Check/Change CMOS Time

The computer CMOS battery will automatically synchronize time with system clock as long as the CMOS is working correctly.

Use the hwclock command to check the CMOS date as follows

# hwclock

check time using hwclock

To synchronize the CMOS date with system date use the following format

# hwclock –systohc

To have the correct time for your Linux environment is critical because many operations depend on it. Such operations include logging events and corn jobs as well. we hope you found this article useful.

Read Also:

[Sep 16, 2019] Artistic Style - Index

Sep 16, 2019 | astyle.sourceforge.net

Artistic Style 3.1 A Free, Fast, and Small Automatic Formatter
for C, C++, C++/CLI, Objective‑C, C#, and Java Source Code

Project Page: http://astyle.sourceforge.net/
SourceForge: http://sourceforge.net/projects/astyle/

Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C++/CLI, Objective‑C, C# and Java programming languages.

When indenting source code, we as programmers have a tendency to use both spaces and tab characters to create the wanted indentation. Moreover, some editors by default insert spaces instead of tabs when pressing the tab key. Other editors (Emacs for example) have the ability to "pretty up" lines by automatically setting up the white space before the code on the line, possibly inserting spaces in code that up to now used only tabs for indentation.

The NUMBER of spaces for each tab character in the source code can change between editors (unless the user sets up the number to his liking...). One of the standard problems programmers face when moving from one editor to another is that code containing both spaces and tabs, which was perfectly indented, suddenly becomes a mess to look at. Even if you as a programmer take care to ONLY use spaces or tabs, looking at other people's source code can still be problematic.

To address this problem, Artistic Style was created – a filter written in C++ that automatically re-indents and re-formats C / C++ / Objective‑C / C++/CLI / C# / Java source files. It can be used from a command line, or it can be incorporated as a library in another program.

[Sep 16, 2019] Usage -- PrettyPrinter 0.18.0 documentation

Sep 16, 2019 | prettyprinter.readthedocs.io

Usage

Install the package with pip :

pip install prettyprinter

Then, instead of

from pprint import pprint

do

from prettyprinter import cpprint

for colored output. For colorless output, remove the c prefix from the function name:

from prettyprinter import pprint

[Sep 16, 2019] JavaScript code prettifier

Sep 16, 2019 | github.com

Announcement: Action required rawgit.com is going away .

An embeddable script that makes source-code snippets in HTML prettier.

[Sep 16, 2019] Pretty-print for shell script

Sep 16, 2019 | stackoverflow.com

Benoit ,Oct 21, 2010 at 13:19

I'm looking for something similiar to indent but for (bash) scripts. Console only, no colorizing, etc.

Do you know of one ?

Jamie ,Sep 11, 2012 at 3:00

Vim can indent bash scripts. But not reformat them before indenting.
Backup your bash script, open it with vim, type gg=GZZ and indent will be corrected. (Note for the impatient: this overwrites the file, so be sure to do that backup!)

Though, some bugs with << (expecting EOF as first character on a line) e.g.

EDIT: ZZ not ZQ

Daniel Martí ,Apr 8, 2018 at 13:52

A bit late to the party, but it looks like shfmt could do the trick for you.

Brian Chrisman ,Sep 9 at 7:47

In bash I do this:
reindent() {
source <(echo "Zibri () {";cat "$1"; echo "}")
declare -f Zibri|head --lines=-1|tail --lines=+3 | sed -e "s/^\s\s\s\s//"
}

this eliminates comments and reindents the script "bash way".

If you have HEREDOCS in your script, they got ruined by the sed in the previous function.

So use:

reindent() {
source <(echo "Zibri () {";cat "$1"; echo "}")
declare -f Zibri|head --lines=-1|tail --lines=+3"
}

But all your script will have a 4 spaces indentation.

Or you can do:

reindent () 
{ 
    rstr=$(mktemp -u "XXXXXXXXXX");
    source <(echo "Zibri () {";cat "$1"|sed -e "s/^\s\s\s\s/$rstr/"; echo "}");
    echo '#!/bin/bash';
    declare -f Zibri | head --lines=-1 | tail --lines=+3 | sed -e "s/^\s\s\s\s//;s/$rstr/    /"
}

which takes care also of heredocs.

> ,

Found this http://www.linux-kheops.com/doc/perl/perl-aubert/fmt.script .

Very nice, only one thing i took out is the [...]->test substitution.

[Sep 16, 2019] A command-line HTML pretty-printer Making messy HTML readable - Stack Overflow

Notable quotes:
"... Have a look at the HTML Tidy Project: http://www.html-tidy.org/ ..."
Sep 16, 2019 | stackoverflow.com

nisetama ,Aug 12 at 10:33

I'm looking for recommendations for HTML pretty printers which fulfill the following requirements:

> ,

Have a look at the HTML Tidy Project: http://www.html-tidy.org/

The granddaddy of HTML tools, with support for modern standards.

There used to be a fork called tidy-html5 which since became the official thing. Here is its GitHub repository .

Tidy is a console application for Mac OS X, Linux, Windows, UNIX, and more. It corrects and cleans up HTML and XML documents by fixing markup errors and upgrading legacy code to modern standards.

For your needs, here is the command line to call Tidy:

[Sep 03, 2019] bash - How to convert strings like 19-FEB-12 to epoch date in UNIX - Stack Overflow

Feb 11, 2013 | stackoverflow.com

Asked 6 years, 6 months ago Active 2 years, 2 months ago Viewed 53k times 24 4

hellish ,Feb 11, 2013 at 3:45

In UNIX how to convert to epoch milliseconds date strings like:
19-FEB-12
16-FEB-12
05-AUG-09

I need this to compare these dates with the current time on the server.

> ,

To convert a date to seconds since the epoch:
date --date="19-FEB-12" +%s

Current epoch:

date +%s

So, since your dates are in the past:

NOW=`date +%s`
THEN=`date --date="19-FEB-12" +%s`

let DIFF=$NOW-$THEN
echo "The difference is: $DIFF"

Using BSD's date command, you would need

$ date -j -f "%d-%B-%y" 19-FEB-12 +%s

Differences from GNU date :

  1. -j prevents date from trying to set the clock
  2. The input format must be explicitly set with -f
  3. The input date is a regular argument, not an option (viz. -d )
  4. When no time is specified with the date, use the current time instead of midnight.

[Sep 03, 2019] Linux - UNIX Convert Epoch Seconds To the Current Time - nixCraft

Sep 03, 2019 | www.cyberciti.biz

Print Current UNIX Time

Type the following command to display the seconds since the epoch:

date +%s

date +%s

Sample outputs:
1268727836

Convert Epoch To Current Time

Type the command:

date -d @Epoch
date -d @1268727836
date -d "1970-01-01 1268727836 sec GMT"

date -d @Epoch date -d @1268727836 date -d "1970-01-01 1268727836 sec GMT"

Sample outputs:

Tue Mar 16 13:53:56 IST 2010

Please note that @ feature only works with latest version of date (GNU coreutils v5.3.0+). To convert number of seconds back to a more readable form, use a command like this:

date -d @1268727836 +"%d-%m-%Y %T %z"

date -d @1268727836 +"%d-%m-%Y %T %z"

Sample outputs:

16-03-2010 13:53:56 +0530

[Sep 03, 2019] command line - How do I convert an epoch timestamp to a human readable format on the cli - Unix Linux Stack Exchange

Sep 03, 2019 | unix.stackexchange.com

Gilles ,Oct 11, 2010 at 18:14

date -d @1190000000 Replace 1190000000 with your epoch

Stefan Lasiewski ,Oct 11, 2010 at 18:04

$ echo 1190000000 | perl -pe 's/(\d+)/localtime($1)/e' 
Sun Sep 16 20:33:20 2007

This can come in handy for those applications which use epoch time in the logfiles:

$ tail -f /var/log/nagios/nagios.log | perl -pe 's/(\d+)/localtime($1)/e'
[Thu May 13 10:15:46 2010] EXTERNAL COMMAND: PROCESS_SERVICE_CHECK_RESULT;HOSTA;check_raid;0;check_raid.pl: OK (Unit 0 on Controller 0 is OK)

Stéphane Chazelas ,Jul 31, 2015 at 20:24

With bash-4.2 or above:
printf '%(%F %T)T\n' 1234567890

(where %F %T is the strftime() -type format)

That syntax is inspired from ksh93 .

In ksh93 however, the argument is taken as a date expression where various and hardly documented formats are supported.

For a Unix epoch time, the syntax in ksh93 is:

printf '%(%F %T)T\n' '#1234567890'

ksh93 however seems to use its own algorithm for the timezone and can get it wrong. For instance, in Britain, it was summer time all year in 1970, but:

$ TZ=Europe/London bash -c 'printf "%(%c)T\n" 0'
Thu 01 Jan 1970 01:00:00 BST
$ TZ=Europe/London ksh93 -c 'printf "%(%c)T\n" "#0"'
Thu Jan  1 00:00:00 1970

DarkHeart ,Jul 28, 2014 at 3:56

Custom format with GNU date :
date -d @1234567890 +'%Y-%m-%d %H:%M:%S'

Or with GNU awk :

awk 'BEGIN { print strftime("%Y-%m-%d %H:%M:%S", 1234567890); }'

Linked SO question: https://stackoverflow.com/questions/3249827/convert-from-unixtime-at-command-line

,

The two I frequently use are:
$ perl -leprint\ scalar\ localtime\ 1234567890
Sat Feb 14 00:31:30 2009

[Sep 03, 2019] Time conversion using Bash Vanstechelman.eu

Sep 03, 2019 | www.vanstechelman.eu

Time conversion using Bash This article show how you can obtain the UNIX epoch time (number of seconds since 1970-01-01 00:00:00 UTC) using the Linux bash "date" command. It also shows how you can convert a UNIX epoch time to a human readable time.

Obtain UNIX epoch time using bash
Obtaining the UNIX epoch time using bash is easy. Use the build-in date command and instruct it to output the number of seconds since 1970-01-01 00:00:00 UTC. You can do this by passing a format string as parameter to the date command. The format string for UNIX epoch time is '%s'.

lode@srv-debian6:~$ date "+%s"
1234567890

To convert a specific date and time into UNIX epoch time, use the -d parameter. The next example shows how to convert the timestamp "February 20th, 2013 at 08:41:15" into UNIX epoch time.

lode@srv-debian6:~$ date "+%s" -d "02/20/2013 08:41:15"
1361346075

Converting UNIX epoch time to human readable time
Even though I didn't find it in the date manual, it is possible to use the date command to reformat a UNIX epoch time into a human readable time. The syntax is the following:

lode@srv-debian6:~$ date -d @1234567890
Sat Feb 14 00:31:30 CET 2009

The same thing can also be achieved using a bit of perl programming:

lode@srv-debian6:~$ perl -e 'print scalar(localtime(1234567890)), "\n"'
Sat Feb 14 00:31:30 2009

Please note that the printed time is formatted in the timezone in which your Linux system is configured. My system is configured in UTC+2, you can get another output for the same command.

[Sep 03, 2019] Run PerlTidy to beautify the code

Notable quotes:
"... Once I installed Code::TidyAll and placed those files in the root directory of the project, I could run tidyall -a . ..."
Sep 03, 2019 | perlmaven.com

The Code-TidyAll distribution provides a command line script called tidyall that will use Perl::Tidy to change the layout of the code.

This tandem needs 2 configuration file.

The .perltidyrc file contains the instructions to Perl::Tidy that describes the layout of a Perl-file. We used the following file copied from the source code of the Perl Maven project.

-pbp
-nst
-et=4
--maximum-line-length=120

# Break a line after opening/before closing token.
-vt=0
-vtc=0

The tidyall command uses a separate file called .tidyallrc that describes which files need to be beautified.

[PerlTidy]
select = {lib,t}/**/*.{pl,pm,t}
select = Makefile.PL
select = {mod2html,podtree2html,pods2html,perl2html}
argv = --profile=$ROOT/.perltidyrc

[SortLines]
select = .gitignore
Once I installed Code::TidyAll and placed those files in the root directory of the project, I could run tidyall -a .

That created a directory called .tidyall.d/ where it stores cached versions of the files, and changed all the files that were matches by the select statements in the .tidyallrc file.

Then, I added .tidyall.d/ to the .gitignore file to avoid adding that subdirectory to the repository and ran tidyall -a again to make sure the .gitignore file is sorted.

[Sep 02, 2019] bash - Pretty-print for shell script

Oct 21, 2010 | stackoverflow.com

Pretty-print for shell script Ask Question Asked 8 years, 10 months ago Active 30 days ago Viewed 14k times


Benoit ,Oct 21, 2010 at 13:19

I'm looking for something similiar to indent but for (bash) scripts. Console only, no colorizing, etc.

Do you know of one ?

Jamie ,Sep 11, 2012 at 3:00

Vim can indent bash scripts. But not reformat them before indenting.
Backup your bash script, open it with vim, type gg=GZZ and indent will be corrected. (Note for the impatient: this overwrites the file, so be sure to do that backup!)

Though, some bugs with << (expecting EOF as first character on a line) e.g.

EDIT: ZZ not ZQ

Daniel Martí ,Apr 8, 2018 at 13:52

A bit late to the party, but it looks like shfmt could do the trick for you.

Brian Chrisman ,Aug 11 at 4:08

In bash I do this:
reindent() {
source <(echo "Zibri () {";cat "$1"; echo "}")
declare -f Zibri|head --lines=-1|tail --lines=+3 | sed -e "s/^\s\s\s\s//"
}

this eliminates comments and reindents the script "bash way".

If you have HEREDOCS in your script, they got ruined by the sed in the previous function.

So use:

reindent() {
source <(echo "Zibri () {";cat "$1"; echo "}")
declare -f Zibri|head --lines=-1|tail --lines=+3"
}

But all your script will have a 4 spaces indentation.

Or you can do:

reindent () 
{ 
    rstr=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1);
    source <(echo "Zibri () {";cat "$1"|sed -e "s/^\s\s\s\s/$rstr/"; echo "}");
    echo '#!/bin/bash';
    declare -f Zibri | head --lines=-1 | tail --lines=+3 | sed -e "s/^\s\s\s\s//;s/$rstr/    /"
}

which takes care also of heredocs.

Pius Raeder ,Jan 10, 2017 at 8:35

Found this http://www.linux-kheops.com/doc/perl/perl-aubert/fmt.script .

Very nice, only one thing i took out is the [...]->test substitution.

[Sep 02, 2019] mvdan-sh A shell parser, formatter, and interpreter (POSIX-Bash-mksh)

Written in Go language
Sep 02, 2019 | github.com
go parser shell bash formatter posix mksh interpreter bash-parser beautify
  1. Go 98.8%
  2. Other 1.2%
Type Name Latest commit message Commit time
Failed to load latest commit information.
_fuzz/ it
_js
cmd
expand
fileutil
interp
shell
syntax
.gitignore
.travis.yml
LICENSE
README.md
go.mod
go.sum
release-docker.sh
README.md

sh

A shell parser, formatter and interpreter. Supports POSIX Shell , Bash and mksh . Requires Go 1.11 or later.

Quick start

To parse shell scripts, inspect them, and print them out, see the syntax examples .

For high-level operations like performing shell expansions on strings, see the shell examples .

shfmt

Go 1.11 and later can download the latest v2 stable release:

cd $(mktemp -d); go mod init tmp; go get mvdan.cc/sh/cmd/shfmt

The latest v3 pre-release can be downloaded in a similar manner, using the /v3 module:

cd $(mktemp -d); go mod init tmp; go get mvdan.cc/sh/v3/cmd/shfmt

Finally, any older release can be built with their respective older Go versions by manually cloning, checking out a tag, and running go build ./cmd/shfmt .

shfmt formats shell programs. It can use tabs or any number of spaces to indent. See canonical.sh for a quick look at its default style.

You can feed it standard input, any number of files or any number of directories to recurse into. When recursing, it will operate on .sh and .bash files and ignore files starting with a period. It will also operate on files with no extension and a shell shebang.

shfmt -l -w script.sh

Typically, CI builds should use the command below, to error if any shell scripts in a project don't adhere to the format:

shfmt -d .

Use -i N to indent with a number of spaces instead of tabs. There are other formatting options - see shfmt -h . For example, to get the formatting appropriate for Google's Style guide, use shfmt -i 2 -ci .

Packages are available on Arch , CRUX , Docker , FreeBSD , Homebrew , NixOS , Scoop , Snapcraft , and Void .

Replacing bash -n

bash -n can be useful to check for syntax errors in shell scripts. However, shfmt >/dev/null can do a better job as it checks for invalid UTF-8 and does all parsing statically, including checking POSIX Shell validity:

$ echo '${foo:1 2}' | bash -n
$ echo '${foo:1 2}' | shfmt
1:9: not a valid arithmetic operator: 2
$ echo 'foo=(1 2)' | bash --posix -n
$ echo 'foo=(1 2)' | shfmt -p
1:5: arrays are a bash feature

gosh

cd $(mktemp -d); go mod init tmp; go get mvdan.cc/sh/v3/cmd/gosh

Experimental shell that uses interp . Work in progress, so don't expect stability just yet.

Fuzzing

This project makes use of go-fuzz to find crashes and hangs in both the parser and the printer. To get started, run:

git checkout fuzz
./fuzz

Caveats

$ echo '${array[spaced string]}' | shfmt
1:16: not a valid arithmetic operator: string
$ echo '${array[dash-string]}' | shfmt
${array[dash - string]}
$ echo '$((foo); (bar))' | shfmt
1:1: reached ) without matching $(( with ))

JavaScript

A subset of the Go packages are available as an npm package called mvdan-sh . See the _js directory for more information.

Docker

To build a Docker image, checkout a specific version of the repository and run:

docker build -t my:tag -f cmd/shfmt/Dockerfile .

Related projects

[May 19, 2010] Converting time since the epoch to a human readable string

April 15, 2010 | Blog O' Matty

I was parsing some Netbackup logs today, and needed a way to convert the time since the epoch into a human readable string. A while back I read about the various forms of input that can be passed to the GNU date's "-d" option, one of these being the time since the epoch:

$ date -d @1263408025
Wed Jan 13 13:40:25 EST 2010

This solved my issue, though unfortunately it's not super portable. Food for thought.

BASH Convert Unix Timestamp to a Date

April 6, 2006 | Anton Olsen.com

I've been asked this a number of times and always have to look it up, so here are 3 ways to convert a unix timestamp (seconds since Jan 1, 1970 GMT) to a real looking date.
Perl method 1: use the ctime module:

perl -e "require 'ctime.pl'; print &ctime($EPOCH);"

Perl method 2: use the scalar and localtime functions:

perl -e "print scalar(localtime($EPOCH))"

Awk has a wrapper for the standard C strftime function:

echo $EPOCH|awk '{print strftime("%c",$1)}'

Here's a sample script that uses all methods.

!#/bin/bash
EPOCH=1000000000
DATE=$(perl -e "require 'ctime.pl'; print &ctime($EPOCH);")
echo $DATE
DATE=$(perl -e "print scalar(localtime($EPOCH))")
echo $DATE
DATE=$(echo $EPOCH|awk '{print strftime("%c",$1)}')
echo $DATE

[update: Thanks to S. Maynard for reminding me of the proper use of quotes and how to avoid using the pipe...]
DATE=$(awk "BEGIN { print strftime(\"%c\",$EPOCH) }")

[UPDATE]

A reader found another way listed below. This doesn't seem to be as portable (The mac ignores the –date and -d is an illegal option).
# date –date='1970-01-01 1000000000 sec GMT'
Sat Sep 8 20:46:40 CDT 2001

[UPDATE]
# date -d @1000000042
Sun Sep 9 01:47:22 GMT 2001

But this only works on newer versions of date. It fails on my FC2 server and my Debian Sarge machine, but works fine on Ubuntu Feisty and Debian Etch.

Date in Unix using Korn Shell - Computing.Net

#This one gives you a day on any given date #from 0001 AD and the dates of the next 5 #weeks.
#Usage is:
#Programname DayOftheMonth Monthoftheyear #Year
#eg dates 26 04 2004


# This function returns the number of days per month
# Requires month and year. NOTE No leading zeros
# Usage dayspm 5 2002

dayspm () {
case $1 in
4|6|9|11) ndays=30
;;
1|3|5|7|8|10|12) ndays=31
;;
2)
if [ `echo "scale=0; $2%4" | bc` -eq 0 ]; then
ndays=29
else
ndays=28
fi
;;
*)
echo "Month Input error"
exit 1
;;
esac
return $ndays
}

if [ $# -eq 3 ]; then
cal $2 $3
day=0
week=`cal $2 $3 | grep -w $1`
year=$3
for pos in 1 4 7 10 13 16 19
do
day=`expr $day + 1`
pos1=`expr $pos + 1`
dpos=`echo "$week" | cut -c$pos-$pos1`
dpos=`echo $dpos`
if [ "$1" = "$dpos" ]; then
case $day in
1) echo "That date is a Sunday"
;;
2) echo "That date is a Monday"
;;
3) echo "That date is a Tuesday"
;;
4) echo "That date is a Wednesday"
;;
5) echo "That date is a Thursday"
;;
6) echo "That date is a Friday"
;;
7) echo "That date is a Saturday"
;;
*) echo "Woooops day error"
;;
esac
month=`expr $2 + 0`
pmonth=$month
ndays=`dayspm $month $3;echo $?`
echo "Next 5 weeks are: "
for nxwk in 7 14 21 28 35
do
week=`expr $1 + $nxwk`
if [ $week -gt $ndays ]; then
month1=`expr $month + 1`
if [ $month1 -gt 12 ]; then
month1=1
fi
pmonth=$month1
week=`expr $week - $ndays`
daysnm=`dayspm $month1 $3;echo $?`
if [ $week -gt $daysnm ]; then
week=`expr $week - $daysnm`
pmonth=`expr $pmonth + 1`
fi

fi
echo "${week}/${pmonth}"
done
fi
done
else
echo Usage $0 day month year
exit 1
fi

Raiden's Realm Using and Understanding the Unix Date Command

01.04.2008

"Date" is a useful little tool that is used to both tell time, and set the time on your Unix, Linux or BSD system. It was first seen in Version 1 of AT&T Unix, circa 1969, and has both grown and improved over the years to provide you with a wide variety of configurable options for your system. Typing "date" at the command line with no other options will render you a fully formatted date, something like this:

Tue Jan 1 20:11:20 EST 2008

As you can see, it's everything you want to know about the current time, but were afraid to ask. All of this is derived from a simple integer number that increments by one number every second. That's how a typical Unix, Linux or BSD system stores its day. The start point for this infinitely increasing number is the Unix Epox, which happened on December 31st, 1969 at 7pm. Was that Eastern Time or Greenwich Mean Time? Who knows. It's simply a starting point for the counter on a Unix, Linux or BSD system to work with when calculating dates.

Here's an example of how that integer number looks: 1199443481

Yes, you're reading that right. There's been (as of the writing of this article) almost 1.2 billion seconds since the Unix Epox. That will happen on January 10th at 4am. It won't roll over to the 1.3 billion mark until May 13th, 2011. Just an interesting little tidbit for you to chew on. It's not worth much at this point, but it's still a fun bit of trivia.

Now, if you want to, you can play around with some of those large numbers inside of data to see what the date and time was when that number appeared in the Unix landscape. For example, let's say we want to find out when 1450000000 will appear. If you type this:

date -r 1450000000

You should get a date like this:

Sun Dec 13 04:46:40 EST 2015

Sadly, this trick only works on Unix and BSD, but not Linux. Not sure why, but the two date applications vary a bit and while there are similarities, there are some unique differences as will be explained later on. Next, we move on to setting the date on your system. The first thing to know before using the date command is that almost everything in your system operates based on the time. So be sure you take extra care when working with this command. It won't format your drive or send your processor into orbit, but it may just mess up how the system does its regular maintenance and operations, and in some cases how security timings are handled.

Now to get started adjusting the time on your system, you will need to be logged in as root at the console to do this. You can also do this as a super user, provided the super user has sufficient privileges. Now, setting the date can be done in any of several ways. The simplest is setting the time. To do that, you would type this:

date 1427

That will set your system time to 2:27pm while leaving the month, day and year alone. But if you want to set the whole kit and caboodle, you would do this:

date 0801051627

That would set the date to January 5, 2008 at 4:27pm. The breakdown of this command is as follows:

2 digit year: 08
2 digit month: 01
2 digit day: 05
2 digit hour in 24 hour format: 16
2 digit minute: 27

Interestingly enough though, this only works in this order on Unix and BSD systems. Linux takes a different approach with the date function. Instead of the 08 being at the beginning, it's at the end. The rest remains the same. So you'd end up with this as your command:

date 0105162708

If you put it in the other order, it will throw the system clock so far forward (up to 2027) that things start crashing randomly due to date issues. Now, another interesting use for the date command is that if you want to add the seconds to this command, you would need to add a decimal number after the 27. But that trick only works on Unix and BSD systems, but not Linux systems. Now, to retrieve the current time format to use on another system to help set it to nearly the same time as your current system, you'll need to do something rather interesting.

For anyone who's ever done programming, you may remember at some point or another having to use percent alphanumeric values with a command to render a given output. The same applies here in some small degree to the date command. If you type in the following command, you can find out what the numerical preset should be:

date "+%Y%m%d%H%M"

The output should look something like this:

200801040628

Of course, on a Linux system, "%Y" will need to be at the end after "%M" in order to generate the correct numerical date format. You can now take that number over to another machine and plug it in by typing "date" and that number as displayed in the examples above. This little article only touches on the bare basics of the "date" command. To learn more, I suggest you hop into your system console sometime and read the man file. You can reach it by typing "man date" at the command prompt. I hope this little article has helped you. If you have any further questions, please feel free to ask in the forums. Thanks.

[Jan 30, 2008] GNU Core-utils / date: Print or set system date and time

date [option]... [+format]
date [-u|--utc|--universal] 
[ MMDDhhmm[[CC]YY][.ss] ]

Invoking date with no format argument is equivalent to invoking `date '+%a %b %e %H:%M:%S %Z %Y''.

If given an argument that starts with a `+', date prints the current time and date (or the time and date specified by the --date option, see below) in the format defined by that argument, which is the same as in the strftime function. Except for directives, which start with `%', characters in the format string are printed unchanged. The directives are described below.

21.1.1 Time directives %[HIklMprsSTXzZ]
21.1.2 Date directives %[aAbBcdDhjmUwWxyY]
21.1.3 Literal directives %[%nt]
21.1.4 Padding Pad with zeroes, spaces (%_), or nothing (%-).
21.1.5 Setting the time Changing the system clock.
21.1.6 Options for date Instead of the current time.
21.1.7 Examples of date Examples.

21.1.1 Time directives

date directives related to times.

`%H'
hour (00...23)
`%I'
hour (01...12)
`%k'
hour ( 0...23)
`%l'
hour ( 1...12)
`%M'
minute (00...59)
`%N'
nanoseconds (000000000...999999999)
`%p'
locale's upper case `AM' or `PM' (blank in many locales)
`%P'
locale's lower case `am' or `pm' (blank in many locales)
`%r'
time, 12-hour (hh:mm:ss [AP]M)
`%R'
time, 24-hour (hh:mm). Same as %H:%M.
`%s'
seconds since the epoch, i.e., 1 January 1970 00:00:00 UTC (a GNU extension). Note that this value is the number of seconds between the epoch and the current date as defined by the localtime system call. It isn't changed by the `--date' option.
`%S'
second (00...60). The range is [00...60], and not [00...59], in order to accommodate the occasional positive leap second.
`%T'
time, 24-hour (hh:mm:ss)
`%X'
locale's time representation (%H:%M:%S)
`%z'
RFC-822 style numeric time zone (e.g., -0600 or +0100), or nothing if no time zone is determinable. This value reflects the current time zone. It isn't changed by the `--date' option.
`%Z'
time zone (e.g., EDT), or nothing if no time zone is determinable. Note that this value reflects the current time zone. It isn't changed by the `--date' option.

21.1.2 Date directives

date directives related to dates.

`%a'
locale's abbreviated weekday name (Sun...Sat)
`%A'
locale's full weekday name, variable length (Sunday...Saturday)
`%b'
locale's abbreviated month name (Jan...Dec)
`%B'
locale's full month name, variable length (January...December)
`%c'
locale's date and time (Sat Nov 04 12:02:33 EST 1989)
`%C'
century (year divided by 100 and truncated to an integer) (00...99)
`%d'
day of month (01...31)
`%D'
date (mm/dd/yy)
`%e'
blank-padded day of month (1...31)
`%F'
the ISO 8601 standard date format: %Y-%m-%d. This is the preferred form for all uses.
`%g'
The year corresponding to the ISO week number, but without the century (range 00 through 99). This has the same format and value as %y, except that if the ISO week number (see %V) belongs to the previous or next year, that year is used instead.
`%G'
The year corresponding to the ISO week number. This has the same format and value as %Y, except that if the ISO week number (see %V) belongs to the previous or next year, that year is used instead.
`%h'
same as %b
`%j'
day of year (001...366)
`%m'
month (01...12)
`%u'
day of week (1...7) with 1 corresponding to Monday
`%U'
week number of year with Sunday as first day of week (00...53). Days in a new year preceding the first Sunday are in week zero.
`%V'
week number of year with Monday as first day of the week as a decimal (01...53). If the week containing January 1 has four or more days in the new year, then it is considered week 1; otherwise, it is week 53 of the previous year, and the next week is week 1. (See the ISO 8601 standard.)
`%w'
day of week (0...6) with 0 corresponding to Sunday
`%W'
week number of year with Monday as first day of week (00...53). Days in a new year preceding the first Monday are in week zero.
`%x'
locale's date representation (mm/dd/yy)
`%y'
last two digits of year (00...99)
`%Y'
year (1970....)

21.1.3 Literal directives

date directives that produce literal strings.

`%%'
a literal %
`%n'
a newline
`%t'
a horizontal tab

21.1.4 Padding

By default, date pads numeric fields with zeroes, so that, for example, numeric months are always output as two digits. GNU date recognizes the following numeric modifiers between the `%' and the directive.

`-'
(hyphen) do not pad the field; useful if the output is intended for human consumption.
`_'
(underscore) pad the field with spaces; useful if you need a fixed number of characters in the output, but zeroes are too distracting.

These are GNU extensions.

Here is an example illustrating the differences:

date +%d/%m -d "Feb 1"
=> 01/02
date +%-d/%-m -d "Feb 1"
=> 1/2
date +%_d/%_m -d "Feb 1"
=>  1/ 2

21.1.5 Setting the time

If given an argument that does not start with `+', date sets the system clock to the time and date specified by that argument (as described below). You must have appropriate privileges to set the system clock. The `--date' and `--set' options may not be used with such an argument. The `--universal' option may be used with such an argument to indicate that the specified time and date are relative to Coordinated Universal Time rather than to the local time zone.

The argument must consist entirely of digits, which have the following meaning:

`MM'
month
`DD'
day within month
`hh'
hour
`mm'
minute
`CC'
first two digits of year (optional)
`YY'
last two digits of year (optional)
`ss'
second (optional)

The `--set' option also sets the system clock; see the next section.

21.1.6 Options for date

The program accepts the following options. Also see 2. Common options.

`-d datestr'
`--date=datestr'
Display the time and date specified in datestr instead of the current time and date. datestr can be in almost any common format. It can contain month names, time zones, `am' and `pm', `yesterday', `ago', `next', etc. See section 27. Date input formats.

`-f datefile'
`--file=datefile'
Parse each line in datefile as with `-d' and display the resulting time and date. If datefile is `-', use standard input. This is useful when you have many dates to process, because the system overhead of starting up the date executable many times can be considerable.

`-I timespec'
`--iso-8601[=timespec]'
Display the date using the ISO 8601 format, `%Y-%m-%d'.

The argument timespec specifies the number of additional terms of the time to include. It can be one of the following:

`auto'
The default behavior: print just the date.

`hours'
Append the hour of the day to the date.

`minutes'
Append the hours and minutes.

`seconds'
Append the hours, minutes, and seconds.

If showing any time terms, then include the time zone using the format `%z'.

If timespec is omitted with `--iso-8601', the default is `auto'. On older systems, GNU date instead supports an obsolete option `-I[timespec]', where timespec defaults to `auto'. POSIX 1003.1-2001 (see section 2.5 Standards conformance) does not allow `-I' without an argument; use `--iso-8601' instead.

`-R'
`--rfc-822'
Display the time and date using the RFC-822-conforming format, `%a, %_d %b %Y %H:%M:%S %z'.

`-r file'
`--reference=file'
Display the time and date reference according to the last modification time of file, instead of the current time and date.

`-s datestr'
`--set=datestr'
Set the time and date to datestr. See `-d' above.

`-u'
`--utc'
`--universal'
Use Coordinated Universal Time (UTC) by operating as if the TZ environment variable were set to the string `UTC0'. Normally, date operates in the time zone indicated by TZ, or the system default if TZ is not set. Coordinated Universal Time is often called "Greenwich Mean Time" (GMT) for historical reasons.

21.1.7 Examples of date

Here are a few examples. Also see the documentation for the `-d' option in the previous section.

[Jan 30, 2008] date (Unix) - Wikipedia, the free encyclopedia

Examples

date "+%-m/%-d/%y" 
7/4/06
date "+%Y%m%d"
20060704

To assign the time to a variable

START=`date '+%r'`
echo $START
03:06:02 PM
sleep 5
echo $START
03:06:02 PM

N.B. the variable has the time when it was assigned.

Yesterday assigned to variable

DATE=$(date -d yesterday +"%Y%m%d")
echo $DATE
20060704

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

Reference



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2020 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) in the author free time and without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: March 05, 2020