do the equivalent of unix date(1) in C

D

Dan Jacobson

Let's say you don't have any more documentation than man pages, and
you want to figure out how to do the equivalent of
$ date
in C. I.e. just simply print out the current date and time. How to
proceed thru the forest of date and time related man pages?
 
G

Gordon Burditt

Let's say you don't have any more documentation than man pages, and
you want to figure out how to do the equivalent of
$ date
in C. I.e. just simply print out the current date and time. How to
proceed thru the forest of date and time related man pages?

1. Call time() to get the current time as a time_t.

#include <time.h>
time_t now;
now = time((time_t *)0);

2. Call localtime() or gmtime() to convert the time_t into a struct tm which
contains the time in more human-understandable terms (month, day, hour, etc).
struct tm *tp;

tp = localtime(&now);
3. Call asctime() or strftime() to format the string the way you want it.
4. printf() the string.

It is possible to combine step 2 and 3 with ctime(), whose format rather
resembles the UNIX date command output except for not including a time zone.

However, getting a time zone name to put in the date command output
has to be done unportably. Some implementations of strftime() may
support %Z for this.

Gordon L. Burditt
 
P

Peter Shaggy Haywood

Groovy hepcat Dan Jacobson was jivin' on Fri, 31 Oct 2003 12:53:09
+0800 in comp.lang.c.
do the equivalent of unix date(1) in C's a cool scene! Dig it!
Let's say you don't have any more documentation than man pages, and
you want to figure out how to do the equivalent of
$ date
in C. I.e. just simply print out the current date and time. How to
proceed thru the forest of date and time related man pages?

Please do your own homework. This is an extremely easy assignment.
I'm sure you can figure it out if you could be bothered to try.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,526
Members
44,997
Latest member
mileyka

Latest Threads

Top