Example of tm use

c tm
tomss picture tomss · Dec 1, 2012 · Viewed 37.2k times · Source

Can you give an example of use of tm (I don't know how to initialize that struct) where the current date is written in this format y/m/d?

Answer

Jomoos picture Jomoos · Dec 1, 2012

How to use tm structure

  1. call time() to get current date/time as number of seconds since 1 Jan 1970.
  2. call localtime() to get struct tm pointer. If you want GMT them call gmtime() instead of localtime().

  3. Use sprintf() or strftime() to convert the struct tm to a string in any format you want.

Example

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

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer [80];

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );

  strftime (buffer,80,"Now it's %y/%m/%d.",timeinfo);
  puts (buffer);

  return 0;
}

Example Output

Now it's 12/10/24

References: