c++ - 如何更新 C++ 中的自定义日期?

标签 c++ date

我创建了自己的 DateTime 类。它接受当前日期/时间,也接受自定义日期/时间。自定义日期/时间是我感兴趣的。

如果我将日期设置为 1/5/1953,时间为下午 1:05:31,并调用 updateTime(),我希望根据首次创建时间和创建时间之间的差异来更新时间之后是毫秒。

但是,当我这样做时,它总是给我今天的日期和时间,这不是我想要的结果。

这是我当前的代码。

if (m_isCustomDate)
{ 
    time_t currentRawTime; 

    // Get the current raw time
    time(&currentRawTime);

    // Get the time lapse  
    time_t time_diff = (time_t)difftime(currentRawTime, m_rawTime);

    // Increment the time difference to the old raw time
    m_rawTime += time_diff;

    // Update the tm structure
    localtime_s(&m_tm, &m_rawTime); 
}

更新问题: 日期为 1/5/1953,时间为下午 1:05:10,当我调用 getSecond() 时,它并没有像我预期的那样给我 10,但它给了我当前的秒数计算机(在本例中为 4 个)。 localtime_s() 不是在这种情况下使用的正确函数吗?

我的 getSecond() 函数:

/// <summary>
/// Gets the current second between 0 and 60.
/// </summary>
/// <returns>Returns the second.</returns>
int DateTime::getSecond()
{
    updateTime();

    return m_tm.tm_sec;
}

更新具体问题: 如何获取原始自定义日期(m_rawTime)与应用程序启动后的时间间隔,然后更新 tm 结构?

编辑: 该解决方案有效。如果有人需要一个工作示例,请发布:

    const DWORD curr_time = GetTickCount();
    DWORD time_diff = (curr_time - m_init_time) / 1000; 

    m_rawTime += time_diff;

    localtime_s(&m_tm, &m_rawTime); 
    m_init_time = curr_time; 

最佳答案

鉴于 m_rawTime 包含“自定义”时间,我注意到以下内容。使用 time_t time_diff = (time_t)difftime(currentRawTime, m_rawTime); 可以得到当前时间和 m_rawTime 之间的时间差。然后,使用 m_rawTime += time_diff; 使 m_rawTime 等于当前时间。我想,这不是你想要做的。

您说您希望时间“根据首次创建时间和之后的毫秒数之间的差异进行更新”。因此,您实际上需要对象上次更新时间与当前时间之间的差异。为此,在构造函数中将一些计数器(例如,this->init_time)初始化为当前时间,并在每次调用 updateTime 时添加当前时间与 this->init_time 之间的差异,并使后者等于当前时间:

void DateTime::updateTime() {
    const auto curr_time = get_time(); // this is not an actual function
    const auto diff = curr_time - this->init_time;

    m_rawTime += diff;
    // update the tm structure here...
    this->init_time = curr_time;
}

现在,如果您想使用毫秒、微秒或更小的时间段,您应该使用 std::chrono::high_resolution_clock但是 struct tm doesn't support时间周期短于一秒,因此您实际上无法使您的自定义时间比使用它更精确。换句话说,如果你坚持 struct tm,你只能以一秒的精度工作,不能再多了。

关于c++ - 如何更新 C++ 中的自定义日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45000619/

相关文章:

c++ - 关于 C++ 未命名命名空间的一些事情

c++ - 使用 Boost JSON 解析器的 JSON 格式化错误

java - 是否有任何java库可以检查给定的日期是否符合字符串中给出的条件?

sql - 在特定日期之前查询没有值

java - 如何在Java中将日期转换为dd.MM.yyyy格式?

c++ - 我需要帮助在 C++ 中尽可能压缩此 IF 语句

c++ - 关于多线程UDP Client-Server架构的问题

c++ - 如何使用 Visual Studio 2012 为 MS-MPI 构建 boost mpi

python - 将当前日期与 CSV 文件匹配并打印匹配项

linux - 从 shell 脚本中的输入接收时间戳