how do i write basic time function

A

Al Bowers

Suresh said:
hello,
i am new to c and how do i use time function to get time.

What do you mean by "get time"? Display?

The Standard provides a time_t type that can hold a value
representing the system time. The Standard offers function
time that can get store in a time_t variable the value
representing the system time.

You can use function ctime to put this
time_t value in printable form(a char string) an then
a stdout function, ie puts, to display.

Example:

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

int main(void)
{
time_t now;

now = time(NULL);
if(now != (time_t)-1) puts(ctime(&now));
else puts("There is no system time");
return 0;
}
 
M

Martin Ambuhl

Suresh said:
hello,
i am new to c and how do i use time function to get time.

#include <stdio.h>
#include <time.h>
#include <string.h>
#define TMBUFSIZ 120 /* only 26 needed for localtime, ctime,
etc */

int main(void)
{
time_t now;
struct tm tyme;
char timebuf[TMBUFSIZ] = "";

now = time(0); /* get the time. A simple line of
'time(&now);' works too. */

/* the short way to show the time */
printf("The time is now (from ctime) %s", ctime(&now));

/* a longer way that sets the struct tm tyme for further use */
tyme = *localtime(&now); /* set up the broken-down time struct */
strcpy(timebuf, asctime(&tyme)); /* We could just printf the
asctime() result as with
ctime above */
printf("The longer way: %s", timebuf);

/* another way to use the struct tm tyme */
strftime(timebuf, TMBUFSIZ, "This is %A, %e %B %Y, %r", &tyme);
printf("Another form: %s\n", timebuf);
return 0;
}

The time is now (from ctime) Sun Apr 25 00:13:38 2004
The longer way: Sun Apr 25 00:13:38 2004
Another form: This is Sunday, 25 April 2004, 12:13:38 AM
 

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

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top