C++ 将当前系统时间转换成标准格式的时间和时间戳

xiaoxiao2021-02-28  10

1:先将系统时间转换成标准格式的时间,再转成时间戳

#include "iostream" #include "time.h" #include "string.h" using namespace std; int main() { time_t rawtime ; struct tm * timeinfo; char s[100]; time ( &rawtime ); timeinfo = localtime ( &rawtime ); time_t tick = mktime(timeinfo); strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", timeinfo); printf("%d: %s\n", (int)tick, s); int Year = timeinfo->tm_year+1900; int Mon = timeinfo->tm_mon+1; int Day = timeinfo->tm_mday; int Hour = timeinfo->tm_hour; int Min = timeinfo->tm_min; int Second = timeinfo->tm_sec; cout << Year << ":" << Mon << ":" << Day << "-" << Hour << ":" << Min << ":" << Second << endl; return 0; }

其中:

int Year = timeinfo->tm_year+1900;

int Mon = timeinfo->tm_mon+1;

其余日,时,分,秒都不变。

运行结果如下:

2:先将系统时间转换成时间戳,再转成标准格式的时间

#include "iostream" #include "time.h" #include "string.h" using namespace std; int main() { time_t now; int unixTime = (int)time(&now); time_t tick = (time_t)unixTime; struct tm tm; char s[100]; tm = *localtime(&tick); strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm); printf("%d: %s\n", (int)unixTime, s); return 0; } 运行结果如下:

转载请注明原文地址: https://www.6miu.com/read-1100269.html

最新回复(0)