Example of tm use

前端 未结 1 799
轮回少年
轮回少年 2021-02-15 20:06

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?

相关标签:
1条回答
  • 2021-02-15 20:31

    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:

    • struct tm
    • strftime
    0 讨论(0)
提交回复
热议问题