头文件:#include <time.h> 、#include <stdio.h>或者#include <iostream>
定义并获取时间:
time_t tTime;
struct tm *locTime;
time(&tTime);//获取当前秒时间
locTime = localtime(&tTime);//转为本地时间
转化为字符串:
char strTime[40];
sprintf(strTime,"%d_%d_%d-%d_%d_%d", locTime->tm_year + 1900, locTime->tm_mon, locTime->tm_mday,
locTime->tm_hour, locTime->tm_min, locTime->tm_sec);//为strTime赋值
其中,结构体tm为:
struct tm {
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 表示从1900年到目前计时时间间隔多少年*/
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
};
例程:
#include <stdio.h>
#include <time.h>
int main()
{
time_t tTime;
struct tm *locTime;
time(&tTime);//获取当前秒时间
locTime = localtime(&tTime);//转为本地时间
char strTime[40];
sprintf(strTime,"%d_%d_%d-%d_%d_%d", locTime->tm_year + 1900, locTime->tm_mon, locTime->tm_mday,
locTime->tm_hour, locTime->tm_min, locTime->tm_sec);//为strTime赋值
printf("%s\n", strTime);
getchar();
return 0;
}