【问题标题】:std::mktime return -1 on QNXQNX 上的 std::mktime 返回 -1
【发布时间】:2023-03-27 12:57:01
【问题描述】:

C++11

在 Ununtu 18 (x64) 和 QNX (x64) 上有一个使用 std::mktime 的跨平台代码

在 Ubuntu 上一切正常。但在 QNX mktime 上返回 -1。错误号 = 3 怎么了?

#include <iostream>
#include "ctime"


int main(int argc, char *argv[]){

    const std::string token = "100901";

    std::string dd = token.substr( 0, 2 );
    std::string mm = token.substr( 2, 2 );
    std::string yy = token.substr( 4, 2 );

    struct std::tm date_tm = {};

    date_tm.tm_mday = std::stoi( dd);
    date_tm.tm_mon = std::stoi( mm) - 1;
    date_tm.tm_year = std::stoi( yy) + 100;

    if (std::mktime( &date_tm ) == -1);
    {
        std::cout << "Error";
    }

    return 0;
}

附:尝试将 init struct tm 设置为:

struct std::tm date_tm = {0};

std::memset( &date_tm, 0, sizeof( date_tm ) )

一些注意事项:

1) 如果我调用 mktime 两次 - 一切都会好起来的(会收到时间)

2) tm 结构打印

tm_gmtoff: 0
tm_hour: 0
tm_isdst: 0
tm_mday: 10
tm_min: 0
tm_mon: 8
tm_sec: 0
tm_wday: 0
tm_yday: 0
tm_year: 101

还有其他(简单快捷)的方法可以在几秒钟内为我的案件节省时间吗?

【问题讨论】:

  • errno的值是多少?
  • @eerorika 值为3
  • 错误信息是什么?使用strerror
  • POSIX 仅规定 mktime 可以 在失败时设置 errno,而不是应该。 QNX 文档根本没有提到它,同时还声称符合 POSIX,所以它可能没有设置。

标签: c++ function time std qnx


【解决方案1】:

在 QNX 设备上,通过设置 tm 结构 tm_isdst = 1 和 tm_zone (GMT) 解决了这个问题

不幸的是,它破坏了我的 Ubuntu 构建(由于时区,在我的本地 PC 上它是 EET)。

将接收秒数替换为 boost::poxis_time

    struct tm date_tm;
    std::memset( &date_tm, 0, sizeof( date_tm ) );
    strptime(token.c_str(), "%d%m%y", &date_tm);

    boost::posix_time::time_duration diff
        = boost::posix_time::ptime( boost::gregorian::date_from_tm( date_tm ) )
          - boost::posix_time::ptime( boost::gregorian::date( 1970, 1, 1 ) );

    date = diff.ticks( ) / boost::posix_time::time_duration::rep_type::ticks_per_second;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    相关资源
    最近更新 更多