start page | rating of books | rating of authors | reviews | copyrights

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 51.9 Making a "Login" ShellChapter 51
Miscellaneous Useful Programs and Curiosities
Next: 51.11 Making an Arbitrary-Size File for Testing
 

51.10 The date Command

All UNIX systems come with a program called date. It shows you the time from the system clock (51.2). (So, the time is only as accurate as your system's clock.) For example:

% date
Fri Dec 13 08:06:39 PST 1996

date
If you need parts of that date, you can split the line into pieces. There are examples in articles 16.18, 21.3, and 2.5. Most newer versions of date (including the one on the Power Tools disc) will also let you set the format of the date. To do that, type a single argument that starts with a plus (+) and has format specification characters in it. Check your online manual page for a list of format specification characters. The argument has to be all one word, so you'll usually need to put quotes (8.14) around it. Here's a simple example:

% date +'Today is %d %h 19%y.'
Today is 13 Dec 1996.

You'll usually use this in a shell script or alias (10.2). Because date can mix any other text with the dates it outputs, you can do some surprising and useful things. Greg Ubben uses it to construct arithmetic expressions for performing calculations on dates. For example, since date +%U isn't available on all systems, the following computes the week number of the year (Sunday as the first day) and makes it available in the Bourne shell as $weekno:

expr `...` 
weekno=`expr \`date +"%j / 7 + ( ( %w + 6 ) %% 7 < %j %% 7 )"\``

For some other "real-life" examples, see articles 16.16, 18.3, and 21.14.

- JP


Previous: 51.9 Making a "Login" ShellUNIX Power ToolsNext: 51.11 Making an Arbitrary-Size File for Testing
51.9 Making a "Login" ShellBook Index51.11 Making an Arbitrary-Size File for Testing

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System