#include <time.h>
time_t timep;
time(&timep); /*获取time_t类型当前时间*/
/*转换为常见的字符串:Fri Jan 11 17:04:08 2008*/
printf("%s", ctime(&timep));
return 0;
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
time_t StringToDatetime(string str)
{
char *cha = (char*)str.data(); // 将string转换成char*。
tm tm_; // 定义tm结构体。
int year, month, day, hour, minute, second;// 定义时间的各个int临时变量。
sscanf(cha, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);// 将string存储的日期时间,转换为int临时变量。
tm_.tm_year = year - 1900; // 年,由于tm结构体存储的是从1900年开始的时间,所以tm_year为int临时变量减去1900。
tm_.tm_mon = month - 1; // 月,由于tm结构体的月份存储范围为0-11,所以tm_mon为int临时变量减去1。
tm_