Tuesday Tiny Techie Tip

date(1) formats

In honor of the new year, let's look at the date command.

By default, date tells you the current date and time:

% date
Mon Jan  6 15:44:21 PST 1997

which is handy to tell you whether it's time to go home yet or not, but if you want to manipulate the values at all, it's pretty clumsy.

Fortunately there are options to manipulate the format. The format option is preceded by a + followed by any number of field descriptors indicated by a % followed by a character to indicate which field is desired. The allowed field descriptors are:

%n=>a newline
%t=>a tab
%m=>month of year (01-12)
%d=>day of month (01-31)
%y=>last two digits of year (00-99)
%D=>date as mm/dd/yy
%H=>hour (00-23)
%M=>minute (00-59)
%S=>second (00-59)
%T=>time as HH:MM:SS
%j=>day of year (001-366)
%w=>day of week (0-6) Sunday is 0
%a=>abbreviated weekday (Sun-Sat)
%h=>abbreviated month (Jan-Dec)
%r=>12-hour time w/ AM/PM (e.g., "03:59:42 PM")

Note that this is all in the date(1) man page, so don't try to memorize it or anything.

So you can almost duplicate the default with a format of "+%a %h %d %T %y":

% date '+%a %h %d %T %y' ; date
Mon Jan 06 16:07:23 97
Mon Jan  6 16:07:23 PST 1997

You can see why I say almost. There's no way with the format to get the timezone, or to get the four-digit year, (Wonder what will happen to the default date output when we click over to 00? ;-) and the day of the month is zero padded instead of space padded. So it's still pretty clumsy, but at least it's tweakable.

Anyway, my favorite application of the format is to generate filenames which always come out in date order when sorted alphabetically in ls(1) output.

% date '+tran.%y%m%d.%H%M%S'

Which I can use in a command line to generate a date/time evident transcript:
% clearmake |& tee `date '+tran.%y%m%d.%H%M%S'`

Which would probably be more useful in a script...
% cat tranmake
fname=`/bin/date '+tran.%y%m%d.%H%M%S'`
/usr/atria/bin/clearmake $* 2>&1 | /bin/tee $tdir/$fname

So tranmake would generate a time-named transcript in my bldtrans directory each time I run it.

There's some other magic there that I'll talk about in a future tip.

For extra credit, what's this one good for: date +%d-%h-%y.%T

Tuesday Tiny Techie Tip -- 7 January 1997
Forward to (01/14/97)
Back to (12/17/96)
Written by Jeff Youngstrom

Up to the TTTT index

Tuesday Tiny Techie Tips are all © Copyright 1996-1997 by Jeff Youngstrom. Please ask permission before reproducing any of this material.