如何使用 strptime(fromdate.c_str(), "%Y-%m-%d %H %M %S", &tm);在 windows

How to use strptime(fromdate.c_str(), "%Y-%m-%d %H %M %S", &tm); on windows

我的代码在 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);

我遇到的错误 `error 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
}

或者,直接 returns std::time_t 的非 throwing 版本:

#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(), "%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) {
        // 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);
}