1.get_time/put_time
//日期转时间戳std::tm tm = {};std::stringstream ss("2020-05-20 13:14:52");ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");time_t timestamp = std::mktime(&tm);std::cout << timestamp << std::endl;//时间戳转日期std::time_t timestamp = std::time(nullptr);std::tm *tm = std::localtime(×tamp);std::stringstream ss;ss << std::put_time(tm,"%Y-%m-%d %H:%M:%S");std::cout << ss.str() << std::endl;
#include <iostream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>using namespace std;
using namespace boost::posix_time;
using namespace boost::gregorian;//字符串转时间戳
template<typename CHAR>
__time64_t Str2Timestamp(const CHAR* str, const CHAR* fmt)
{std::basic_istringstream<CHAR> is(str);std::tm tm = {};is >> std::get_time(&tm, fmt);return std::mktime(&tm);
}//时间戳转字符串
template<typename CHAR>
std::basic_string<CHAR> Timestamp2Str(__time64_t timestamp,const CHAR* fmt)
{std::tm cur_tm = *(std::localtime(×tamp));std::basic_ostringstream<CHAR> os;os << std::put_time(&cur_tm, fmt);return os.str();
}int main()
{std::string str_timestamp = Timestamp2Str(time(NULL), "%Y:%m:%d %H:%M:%S").c_str();std::cout << str_timestamp << std::endl;std::cout << Str2Timestamp(str_timestamp.c_str(),"%Y:%m:%d %H:%M:%S") << std::endl;
}
2.ctime库转换
//1.CLOCKS_PER_SEC: 表示一秒钟会有多少个时钟计时单元。clock_t start, finish;start = clock();long i = 10000000L;while(i--); finish = clock();double duration = (double)(finish - start) / CLOCKS_PER_SEC;printf("%f seconds/n", duration); // 0.000002 seconds//2.获取当前日期: time_t now = time(0);std::cout << "当前秒数:" << now << std::endl; // 1572610824char* dt = ctime(&now);std::cout << "CST 本地日期和时间:" << dt << std::endl; // Fri Nov 1 20:20:24 2019tm *gmtm = gmtime(&now);dt = asctime(gmtm);std::cout << "UTC 日期和时间:"<< dt << std::endl; // Fri Nov 1 12:20:24 2019//3.日期转秒数tm t;t.tm_year = 2019 - 1900;t.tm_mon = 9 - 1;t.tm_mday = 1;t.tm_hour = 0; t.tm_min = 0; t.tm_sec = 0; time_t timestamp = mktime(&t);std::cout << "2019-09-01秒数:" << timestamp << std::endl; // 1567267200//4.秒数转日期time_t now(1567267200);char* dt = ctime(&now);std::cout << "对应的 CST 时间:" << dt << std::endl; // Sun Sep 1 00:00:00 2019tm *gmtm = gmtime(&now);dt = asctime(gmtm);std::cout << "对应的 UTC 时间:"<< dt << std::endl; // Sat Aug 31 16:00:00 2019tm *ltm = localtime(&now);std::cout << "年: " << 1900 + ltm->tm_year << std::endl; // 2019std::cout << "月: " << 1 + ltm->tm_mon<< std::endl; // 9std::cout << "日: " << ltm->tm_mday << std::endl; // 1std::cout << "时: " << ltm->tm_hour << std::endl; // 0std::cout << "分: " << ltm->tm_min << std::endl; // 0std::cout << "秒: " << ltm->tm_sec << std::endl; // 0