Simple Demo
1 2 3 4 5 6 7 8 9 10 11
| #include <iostream> #include <time.h> using namespace std;
int main() { time_t t; time(&t); cout << t <<endl; return 0; }
|
以上代码会输出一个10位数,表示的是到当前时间的秒数,起点是 1970年1月1日 00:00:00
time_t 转换
-
string 转 time_t
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| time_t StringToDatetime(std::string str) { char *cha = (char*)str.data(); tm tm_; int year, month, day, hour, minute, second; sscanf(cha, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second); tm_.tm_year = year - 1900; tm_.tm_mon = month - 1; tm_.tm_mday = day; tm_.tm_hour = hour; tm_.tm_min = minute; tm_.tm_sec = second; tm_.tm_isdst = 0; time_t t_ = mktime(&tm_); return t_; }
|
-
time_t 转 string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| (1) time_t t=std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); std::stringstream ss; ss<<std::put_time(std::localtime(&t),"%F %X"); ss.str(); (2) size_t strftime (char* ptr, size_t maxsize, const char* format, const struct tm* timeptr ); ptr:存储转换结果 maxsize:复制到ptr的最大字符数,包括结束符'\0' format:转换格式,类似printf,可加入其他需要复制过去的字符 timeptr:时间 char buf[20]; tm* local_time = std::localtime(&t); strftime(buf,sizeof(buf),"%F %X",local_time);
|
C++时间类
使用C++时间类处理获取系统当前时间 日期和时间工具 - C++中文 - API参考文档 (apiref.com)
头文件 #include <chrono>
- 获取当前时间
1
| system_clock::time_point now = std::chrono::system_clock::now();
|
- 将当前时间转换为time_格式
1
| time_t tt = std::chrono::system_clock::to_time_t(now);
|
- 将time_格式的时间转换为tm *格式
1
| struct tm* tmNow = localtime(&tt);
|
- 将tm*格式的时间转换为可读的时间
1 2
| char date[20] = { 0 }; sprintf(date, "%d-%02d-%02d %02d:%02d:%02d",(int)tmNow->tm_year + 1900, (int)tmNow->tm_mon + 1, (int)tmNow->tm_mday, (int)tmNow->tm_hour, (int)tmNow->tm_min, (int)tmNow->tm_sec);
|
最后,在C++中的话可以将char*字符串转换为std::string字符串来处理
1
| std::string timeNow(date);
|