how do i write basic time function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Suresh

    #1

    how do i write basic time function

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

    thanks,
    Sean


  • Al Bowers

    #2
    Re: how do i write basic time function



    Suresh wrote:[color=blue]
    > hello,
    > i am new to c and how do i use time function to get time.[/color]

    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;
    }


    --
    Al Bowers
    Tampa, Fl USA
    mailto: xabowers@myrapi dsys.com (remove the x to send email)
    Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!


    Comment

    • Martin Ambuhl

      #3
      Re: how do i write basic time function

      Suresh wrote:
      [color=blue]
      > hello,
      > i am new to c and how do i use time function to get time.[/color]

      #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(timebu f, 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

      Comment

      Working...