Time Function

This is a discussion on Time Function within the C Programming forums, part of the General Programming Boards category; Hi, I'm trying to extract just the time element from time() my code at present is. Code: time_t now; char ...

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    23

    Time Function

    Hi,

    I'm trying to extract just the time element from time()

    my code at present is.

    Code:
     time_t now;
        char buff[MAX_LEN];
        time(&now);
        printf("%s\n", ctime(&now));
    Which prints for example,

    Thu May 20 11:40:56 2004

    how do i change it to just extract the 11:40:56

    Thanks

  2. #2
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    I would use localtime in time.h Then you could get the information from the structure

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    You could use strftime.
    Code:
    #include <stdio.h>
    #include <time.h>
    
    int main(void)
    {
       time_t now;
       if ( time(&now) != (time_t)(-1) )
       {
          struct tm *mytime = localtime(&now);
          if ( mytime )
          {
             char buffer [ 32 ];
             if ( strftime(buffer, sizeof buffer, "%X", mytime) )
             {
                printf("buffer = \"%s\"\n", buffer);
             }
          }
       }
       return 0;
    }
    
    /* my output
    buffer = "09:09:26"
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  4. #4
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    Posts
    501
    I usually always forget about strftime, very handy for printing, not much use when doing algorithms and stuff, so I usually end up doing what linuxdude suggested, but strftime is the better alternative.
    Help populate a c/c++ help irc channel
    server: irc://irc.efnet.net
    channel: #c

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  2. Sending an email in C program
    By Moony in forum C Programming
    Replies: 28
    Last Post: 10-19-2006, 10:42 AM
  3. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  4. Replies: 5
    Last Post: 02-08-2003, 06:42 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21