|
Home | Switchboard | Unix Administration | Red Hat | TCP/IP Networks | Neoliberalism | Toxic Managers |
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and bastardization of classic Unix |
|
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.
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 your 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 |
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
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.
Here are most important build-in macros:
- %% a literal %
- %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)
- %d day of month (01..31)
- %D date (mm/dd/yy)
- %e day of month, blank padded ( 1..31)
- %H hour (00..23)
- %j day of year (001..366)
- %m month (01..12)
- %M minute (00..59)
- %n a newline
- %p locale's AM or PM
- %r time, 12-hour (hh:mm:ss [AP]M)
- %S second (00..60)
- %t a horizontal tab
- %T time, 24-hour (hh:mm:ss)
- %U week number of year with Sunday as first day of week (00..53)
- %V week number of year with Monday as first day of week (01..52)
- %w day of week (0..6); 0 represents Sunday
- %W week number of year with Monday as first day of week (00..53)
- %x locale's date representation (mm/dd/yy)
- %X locale's time representation (%H:%M:%S)
- %y last two digits of year (00..99)
- %Y -- ccyy year
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
|
Switchboard | ||||
Latest | |||||
Past week | |||||
Past month |
Jun 10, 2021 | vitux.com
Displaying Date From String
We can display the formatted date from the date string provided by the user using the -d or ""date option to the command. It will not affect the system date, it only parses the requested date from the string. For example,
$ date -d "Feb 14 1999"Parsing string to date.
$ date --date="09/10/1960"Parsing string to date.
Displaying Upcoming Date & Time With -d OptionAside from parsing the date, we can also display the upcoming date using the -d option with the command. The date command is compatible with words that refer to time or date values such as next Sun, last Friday, tomorrow, yesterday, etc. For examples,
Displaying Next Monday Date$ date -d "next Mon"
Displaying upcoming date.
Displaying Past Date & Time With -d OptionUsing the -d option to the command we can also know or view past date. For examples,
Displaying Last Friday Date$ date -d "last Fri"Displaying past date
Parse Date From FileIf you have a record of the static date strings in the file we can parse them in the preferred date format using the -f option with the date command. In this way, you can format multiple dates using the command. In the following example, I have created the file that contains the list of date strings and parsed it with the command.
$ date -f datefile.txtParse date from the file.
Setting Date & Time on LinuxWe can not only view the date but also set the system date according to your preference. For this, you need a user with Sudo access and you can execute the command in the following way.
$ sudo date -s "Sun 30 May 2021 07:35:06 PM PDT"Display File Last Modification TimeWe can check the file's last modification time using the date command, for this we need to add the -r option to the command. It helps in tracking files when it was last modified. For example,
$ date -r /etc/hosts
Mar 09, 2021 | www.xmodulo.com
When you calldate
with+%s
option, it shows the current system clock in seconds since 1970-01-01 00:00:00 UTC. Thus, with this option, you can easily calculate time difference in seconds between two clock measurements.start_time=$(date +%s) # perform a task end_time=$(date +%s) # elapsed time with second resolution elapsed=$(( end_time - start_time ))Another (preferred) way to measure elapsed time in seconds in bash is to use a built-in bash variable called
SECONDS
. When you accessSECONDS
variable in a bash shell, it returns the number of seconds that have passed so far since the current shell was launched. Since this method does not require running the externaldate
command in a subshell, it is a more elegant solution.start_time=$SECONDS sleep 5 elapsed=$(( SECONDS - start_time )) echo $elapsedThis will display elapsed time in terms of the number of seconds. If you want a more human-readable format, you can convert
$elapsed
output as follows.eval "echo Elapsed time: $(date -ud "@$elapsed" +'$((%s/3600/24)) days %H hr %M min %S sec')"This will produce output like the following.
Elapsed time: 0 days 13 hr 53 min 20 sec
Jan 01, 2017 | unix.stackexchange.com
491k 109 965 1494 asked Aug 22 '14 at 9:40 SHW 7,341 3 31 69
> ,
- 1
Christian Severin , 2017-09-29 09:47:52
You can use e.g.date --set='-2 years'
to set the clock back two years, leaving all other elements identical. You can change month and day of month the same way. I haven't checked what happens if that calculation results in a datetime that doesn't actually exist, e.g. during a DST switchover, but the behaviour ought to be identical to the usual "set both date and time to concrete values" behaviour. – Christian Severin Sep 29 '17 at 9:47Michael Homer , 2014-08-22 09:44:23
Usedate -s
:date -s '2014-12-25 12:34:56'Run that as root or under
sudo
. Changing only one of the year/month/day is more of a challenge and will involve repeating bits of the current date. There are also GUI date tools built in to the major desktop environments, usually accessed through the clock.To change only part of the time, you can use command substitution in the date string:
date -s "2014-12-25 $(date +%H:%M:%S)"will change the date, but keep the time. See
man date
for formatting details to construct other combinations: the individual components are%Y
,%m
,%d
,%H
,%M
, and%S
.> ,
> , 2014-08-22 09:51:41
I don't want to change the time – SHW Aug 22 '14 at 9:51Michael Homer , 2014-08-22 09:55:00
There's no option to do that. You can usedate -s "2014-12-25 $(date +%H:%M:%S)"
to change the date and reuse the current time, though. – Michael Homer Aug 22 '14 at 9:55chaos , 2014-08-22 09:59:58
System timeYou can use
date
to set the system date. The GNU implementation ofdate
(as found on most non-embedded Linux-based systems) accepts many different formats to set the time, here a few examples:set only the year:
date -s 'next year' date -s 'last year'set only the month:
date -s 'last month' date -s 'next month'set only the day:
date -s 'next day' date -s 'tomorrow' date -s 'last day' date -s 'yesterday' date -s 'friday'set all together:
date -s '2009-02-13 11:31:30' #that's a magical timestampHardware time
Now the system time is set, but you may want to sync it with the hardware clock:
Use
--show
to print the hardware time:hwclock --showYou can set the hardware clock to the current system time:
hwclock --systohcOr the system time to the hardware clock
hwclock --hctosys> ,
- 2
garethTheRed , 2014-08-22 09:57:11
You change the date with thedate
command. However, the command expects a full date as the argument:# date -s "20141022 09:45" Wed Oct 22 09:45:00 BST 2014To change part of the date, output the current date with the date part that you want to change as a string and all others as date formatting variables. Then pass that to the
date -s
command to set it:# date -s "$(date +'%Y12%d %H:%M')" Mon Dec 22 10:55:03 GMT 2014changes the month to the 12th month - December.
The date formats are:
%Y
- Year%m
- Month%d
- Day%H
- Hour%M
- MinuteBalmipour , 2016-03-23 09:10:21
For ones like me running ESXI 5.1, here's what the system answered me~ # date -s "2016-03-23 09:56:00" date: invalid date '2016-03-23 09:56:00'I had to uses a specific ESX command instead :
esxcli system time set -y 2016 -M 03 -d 23 -H 10 -m 05 -s 00Hope it helps !
> ,
- 1
Brook Oldre , 2017-09-26 20:03:34
I used the date command and time format listed below to successfully set the date from the terminal shell command performed on Android Things which uses the Linux Kernal.date 092615002017.00
MMDDHHMMYYYY.SS
MM - Month - 09
DD - Day - 26
HH - Hour - 15
MM - Min - 00
YYYY - Year - 2017
.SS - second - 00
> ,
Time and date specified by the ISO 8601 standard, for example2005-04-07T22:13:13
. The parser accepts a space instead of theT
character as well.Note
In addition, the date part is accepted in the following formats:YYYY.MM.DD
,MM/DD/YYYY
andDD.MM.YYYY
.
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 2010This solved my issue, though unfortunately it's not super portable. Food for thought.
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 2001But 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.
#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 2002dayspm () {
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`
fifi
echo "${week}/${pmonth}"
done
fi
done
else
echo Usage $0 day month year
exit 1
fi
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: 27Interestingly 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.
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 thestrftime
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
through99
). 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. GNUdate
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/ 221.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 byTZ
, or the system default ifTZ
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.
- To print the date of the day before yesterday:
date --date='2 days ago'
- To print the date of the day three months and one day hence:
date --date='3 months 1 day'
- To print the day of year of Christmas in the current year:
date --date='25 Dec' +%j
- To print the current full month name and the day of the month:
date '+%B %d'But this may not be what you want because for the first nine days of the month, the `%d' expands to a zero-padded two-digit field, for example `date -d 1may '+%B %d'' will print `May 01'.
- To print a date without the leading zero for one-digit days of the month, you can use the (GNU extension)
-
modifier to suppress the padding altogether.
date -d 1may '+%B %-d
- To print the current date and time in the format required by many non-GNU versions of
date
when setting the system clock:
date +%m%d%H%M%Y.%S
- To set the system clock forward by two minutes:
date --set='+2 minutes'
- To print the date in the format specified by RFC-822, use `date --rfc'. I just did and saw this:
Mon, 25 Mar 1996 23:34:17 -0600
- To convert a date string to the number of seconds since the epoch (which is 1970-01-01 00:00:00 UTC), use the `--date' option with the `%s' format. That can be useful in sorting and/or graphing and/or comparing data by date. The following command outputs the number of the seconds since the epoch for the time two minutes after the epoch:
date --date='1970-01-01 00:02:00 +0000' +%s 120If you do not specify time zone information in the date string,
date
uses your computer's idea of the time zone when interpreting the string. For example, if your computer's time zone is that of Cambridge, Massachusetts, which was then 5 hours (i.e., 18,000 seconds) behind UTC:
# local time zone used date --date='1970-01-01 00:02:00' +%s 18120- If you're sorting or graphing dated data, your raw date values may be represented as seconds since the epoch. But few people can look at the date `946684800' and casually note "Oh, that's the first second of the year 2000 in Greenwich, England."
date --date='2000-01-01 UTC' +%s 946684800To convert such an unwieldy number of seconds back to a more readable form, use a command like this:
# local time zone used date -d '1970-01-01 UTC 946684800 seconds' +"%Y-%m-%d %T %z" 1999-12-31 19:00:00 -0500
Examples
date "+%-m/%-d/%y" 7/4/06date "+%Y%m%d" 20060704To assign the time to a variable
START=`date '+%r'` echo $START 03:06:02 PM sleep 5 echo $START 03:06:02 PMN.B. the variable has the time when it was assigned.
Yesterday assigned to variable
DATE=$(date -d yesterday +"%Y%m%d") echo $DATE 20060704
Google matched content |
date - print or set the system date and time
Display the current time in the given FORMAT, or set the system date.
FORMAT controls the output. The only valid option for the second form specifies Coordinated Universal Time. Interpreted sequences are:
By default, date pads numeric fields with zeroes. GNU date recognizes the following modifiers between `%' and a numeric directive.
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 quotes : Somerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Bernard 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 DOS : Programming Languages History : PL/1 : Simula 67 : C : History of GCC development : Scripting 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-Month : How 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-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) 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 to buy a cup of coffee for authors of this site |
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 Softpanorama society. 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: December 13, 2020