1. 获取当前时间字符串
#include <time.h>
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%4d-%02d-%02d %02d:%02d:%02d\n",
tm->tm_year + 1900, tm->tm_mon + 1,
tm->tm_mday, tm->tm_hour,
tm->tm_min, tm->tm_sec);
2. 字符串转 时间
#include <iostream>
#include <fstream>
#include <time.h>
using namespace std;
int main(int argc, char *argv[]) {
time_t tt = time(NULL);
cout << (long)tt <<endl;
const char*date="2012-02-14 14:00:00"; //这个时间格式 必须与strptime中相同
tm t;
if (strptime(date,"%Y-%m-%d %H:%M:%S",&t)) {
time_t ttt=mktime(&t);
cout <<(long)ttt <<endl;
printf("%d/%d/%d %d:%d:%d\n",t.tm_year+1900,
t.tm_mon+1,t.tm_mday,t.tm_hour, t.tm_min, t.tm_sec);
} else
cout << "strptime error.";
}