问题
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:
How to use tm
structure
- call
time()
to get current date/time as number of seconds since 1 Jan 1970. call
localtime()
to getstruct tm
pointer. If you want GMT them callgmtime()
instead oflocaltime()
.Use
sprintf()
orstrftime()
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
来源:https://stackoverflow.com/questions/13658756/example-of-tm-use