Time - Displaying Current

Dave Sinkula 0 Tallied Votes 128 Views Share

This snippet shows how to use the functions time , localtime , and strftimetime to pick off only the time parts for display.

#include <stdio.h>
#include <time.h>
 
int main(void)
{
   time_t now;
   /*
    * The next line attempts to get the current time.
    * The result is stored in 'now'.
    * If the call to time() fails, it returns (time_t)(-1); verify success
    * before continuing on.
    */
   if ( time(&now) != (time_t)(-1) )
   {
      /*
       * Declare a variable 'mytime' and initialize it to a pointer to the
       * result of calling localtime().
       * The localtime() function converts the calendar time in 'now' into a
       * broken-down time, expressed as local time.
       * This is needed for the call to strftime().
       */
      struct tm *mytime = localtime(&now);
      /*
       * If localtime() fails, it returns a null pointer; verify success before
       * continuing on.
       */
      if ( mytime )
      {
         char buffer [ 32 ];
         /*
          * Use strftime() to create a string representation of the broken-down
          * time.
          * If strftime() fails, zero is returned and the contents of the array
          * are indeterminate; verify success before continuing on.
          */
         if ( strftime(buffer, sizeof buffer, "%X", mytime) )
         {
            /*
             * We were able to get the current time, we were able to convert
             * this value to local time and point to its structure, we were able
             * to create a string in our chosen format, so let's print it.
             * The double quotes help show the full contents of the string we
             * have created.
             */
            printf("buffer = \"%s\"\n", buffer);
         }
      }
   }
   return 0;
}
 
/* my output
buffer = "09:09:26"
*/
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.