问题描述
我有一个在 Windows 上运行良好的代码,我必须让它与 Linux 兼容。 谁能帮我将以下代码片段配置到 Windows 中?
MongoDB* db = MongoDB::getInstance();
mongocxx::pipeline p{};
struct tm tm;
strptime(fromdate.c_str(),"%Y-%m-%d %H %M %s",&tm); //this line gives me some errors
std::time_t tt = std::mktime(&tm);
我得到的错误 `错误 C3861:'strptime':未找到标识符
我尝试使用 http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD 中的代码
但它也给出了一些错误,因为它说缺少一些头文件,例如 #include <sys/cdefs.h>
,#include "namespace.h"
谁能告诉我如何在项目中包含这些头文件或任何其他解决此问题的方法 提前致谢
解决方法
如果您无法使 strptime
的 BSD 版本正常工作,您可以尝试 Howard Hinnant's date.h
或者您可以自己为这种特定格式创建一个简单的转换函数。示例:
#include <cstdio>
#include <ctime>
#include <cerrno>
#include <iostream>
#include <stdexcept>
#include <string>
#include <string_view>
std::tm to_tm(const std::string_view& date) {
std::tm t{};
if(std::sscanf(date.data(),"%d-%d-%d %d %d %d",&t.tm_year,&t.tm_mon,&t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec
) != 6)
throw std::runtime_error("Invalid date format: " + std::string(date));
t.tm_year -= 1900;
--t.tm_mon;
t.tm_isdst = -1; // guess if DST should be in effect when calling mktime
errno = 0;
std::mktime(&t);
return t;
}
int main() {
std::string fromdate = "2021-03-25 08 23 56";
std::tm x = to_tm(fromdate);
std::cout << std::asctime(&x) << '\n'; // Thu Mar 25 08:23:56 2021
}
或者,直接返回 throw
的非std::time_t
版本:
#include <system_error> // added to be able to set an error code
std::time_t to_time_t(const std::string_view& date) {
std::tm t{};
if(std::sscanf(date.data(),&t.tm_sec
) != 6) {
// EOVERFLOW (std::errc::value_too_large)
// This is what Posix versions of mktime() uses to signal that -1 does
// not mean one second before epoch,but that there was an error.
errno = static_cast<int>(std::errc::value_too_large);
return -1;
}
t.tm_year -= 1900;
--t.tm_mon;
t.tm_isdst = -1; // guess if DST should be in effect when calling mktime
errno = 0;
return std::mktime(&t);
}