我知道这些价值
unsigned char year = 17; // means 2017
unsigned char month = 8;
unsigned char day = 25;
unsigned char hour = 14;
unsigned char minute = 23;
unsigned char second = 54;
如何将这些转换为unix时间戳?我不确定unsigned char
是否是表示值的正确方法,我只需要每个值大小为1byte。
答案 0 :(得分:2)
Ubervan回答了你的问题
将日期分解为其组成部分,即日,月,年,然后:
struct tm tm;
time_t rawtime;
time ( &rawtime );
tm = *localtime ( &rawtime );
tm.tm_year = year - 1900;
tm.tm_mon = month - 1;
tm.tm_mday = day;
mktime(&tm);
tm现在可以转换为time_t并进行操作。
您的问题也已解决here。
答案 1 :(得分:1)
也许最简单,性能最高的方法是使用Howard Hinnant's free, open-source, header-only datetime library:
#include "date.h"
#include <iostream>
date::sys_seconds
to_sys_time(unsigned char y, unsigned char m, unsigned char d,
unsigned char h, unsigned char M, unsigned char s)
{
using namespace date;
using namespace std::chrono;
return sys_days{year{y+2000}/m/d} + hours{h} + minutes{M} + seconds{s};
}
int
main()
{
std::cout << to_sys_time(17, 9, 25, 14, 23, 54).time_since_epoch().count() << '\n';
}
输出:
1503671034
此库扩展了<chrono>
库以处理日历计算,并且是even being proposed for standardization。
答案 2 :(得分:0)
这就是我如何接受c ++ 11的更多内容。
std::string timepointToString(std::chrono::system_clock::time_point const& t) {
time_t tt = std::chrono::system_clock::to_time_t(t);
struct tm tb;
size_t const len(21);
char buffer[len];
TRI_gmtime(tt, &tb);
::strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%SZ", &tb);
return std::string(buffer, len - 1);
}
std::chrono::system_clock::time_point stringToTimepoint(std::string const& s) {
if (!s.empty()) {
try {
std::tm tt;
tt.tm_year = std::stoi(s.substr(0, 4)) - 1900;
tt.tm_mon = std::stoi(s.substr(5, 2)) - 1;
tt.tm_mday = std::stoi(s.substr(8, 2));
tt.tm_hour = std::stoi(s.substr(11, 2));
tt.tm_min = std::stoi(s.substr(14, 2));
tt.tm_sec = std::stoi(s.substr(17, 2));
tt.tm_isdst = 0;
auto time_c = TRI_timegm(&tt);
return std::chrono::system_clock::from_time_t(time_c);
} catch (...) {}
}
return std::chrono::time_point<std::chrono::system_clock>();
}