微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我有一个在 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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。