prev up next   top/contents search

comp.lang.c FAQ list · Question 13.12

Q: How can I get the current date or time of day in a C program?


A: Just use the time, ctime, localtime and/or strftime functions. Here is a simple example: [footnote]

#include <stdio.h>
#include <time.h>

int main()
{
	time_t now;
	time(&now);
	printf("It's %s", ctime(&now));
	return 0;
}

Calls to localtime and strftime look like this:

	struct tm *tmp = localtime(&now);
	char fmtbuf[30];
	printf("It's %d:%02d:%02d\n",
		tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
	strftime(fmtbuf, sizeof fmtbuf, "%A, %B %d, %Y", tmp);
	printf("on %s\n", fmtbuf);
(Note that these functions take a pointer to the time_t variable, even when they will not be modifying it.[footnote] )

If you need sub-second resolution, see question 19.37.

References: K&R2 Sec. B10 pp. 255-7
ISO Sec. 7.12
H&S Sec. 18


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North