生活随笔
收集整理的這篇文章主要介紹了
linux下unix timestamp 与 可视化时间/常规时间进行转换
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
unix timestamp 與 可視化時(shí)間/常規(guī)時(shí)間進(jìn)行轉(zhuǎn)換。
最近工作中需要根據(jù)可視化時(shí)間得到unix timestamp,完成工作之后記錄下來了,防止下次遇到此問題時(shí),又需要重新梳理,直接上代碼了
:
#include <iostream>
#include <string>
#include <ctime>
#include <string.h>void unix_timestamp_2_str(long timestamp, char strTime[], int bufLen) {struct tm tm = *localtime((time_t *)×tamp);strftime(strTime, bufLen - 1, "%Y-%m-%d %H:%M:%S", &tm);strTime[bufLen - 1] = '\0';
}time_t strtime_2_unix_timestamp(const char *timestamp) {struct tm tm;memset(&tm, 0, sizeof(tm));sscanf(timestamp, "%d-%d-%d %d:%d:%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday,&tm.tm_hour, &tm.tm_min, &tm.tm_sec);tm.tm_year -= 1900;tm.tm_mon--;return mktime(&tm);
}int main () {char strTime[100] = {0};long now_timestamp = 1619716862;unix_timestamp_2_str(now_timestamp, strTime, sizeof(strTime));std::cout << "timestamp=" << now_timestamp << " ---> strTime=" << strTime << std::endl;std::string strtime("2021-04-29 17:21:02");time_t timestamp = strtime_2_unix_timestamp(strtime.c_str());std::cout << "timestamp = " << timestamp << "----> strtime=" << ctime(×tamp) << std::endl;return 0;
}
?
結(jié)果如下:
?
timestamp=1619716862 ---> strTime=2021-04-29 17:21:02strtime=Thu Apr 29 17:21:02 2021---> timestamp = 1619716862
注意點(diǎn):
(1)、timestamp的類型是long,與time_t一致。
(2)、unix timestamp是一個(gè)long類型的值,從1970年1月1日00:00::00到本時(shí)刻經(jīng)歷的second數(shù)。
?
?
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的linux下unix timestamp 与 可视化时间/常规时间进行转换的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。