如何从C ++中的当前日期开始两周内获取时间戳(以毫秒为单位)?

时间:2014-08-05 23:59:32

标签: c++ timestamp milliseconds

我需要计算从当前日期起两周的日期的时间戳(以毫秒为单位)。

截至目前,这是我计算当前时间戳的方式,以毫秒为单位 -

struct timeval tp;
gettimeofday(&tp, NULL);
uint64_t current_ms = tp.tv_sec * 1000 + tp.tv_usec / 1000; //get current timestamp in milliseconds

现在我不知道如何从当前日期开始的两周内获得时间戳(以毫秒为单位)?我有兴趣创建一个函数,它返回从当前日期开始的两周内的时间戳(以毫秒为单位)。

我最近开始使用C ++,因此不确定在两周内查看时间戳(以毫秒为单位)的正确方法。我将在Ubuntu 12.04上运行此代码。

更新: -

以下是我的代码 -

#include <ctime>
#include <chrono>
#include <iostream>

int main()
{
    const auto now = std::chrono::system_clock::now();
    auto twoWeeks = std::chrono::hours(24 * 14);
    auto lastTwoWeeks = now - twoWeeks;

    auto millis = std::chrono::duration_cast<std::chrono::milliseconds>\
                    (lastTwoWeeks.time_since_epoch()).count();
    std::cout << "Time stamp in milliseconds since UNIX epoch start: "\
              << millis << std::endl;

    return 0;
}

2 个答案:

答案 0 :(得分:1)

使用C ++ 11,以下内容可能有所帮助:

#include <ctime>
#include <chrono>
#include <iostream>

int main()
{
    const auto now = std::chrono::system_clock::now();
    auto twoWeeks = std::chrono::hours(24 * 14);
    auto lastTwoWeeks = now - twoWeeks;

    // display time_point:
    std::time_t tt = std::chrono::system_clock::to_time_t(lastTwoWeeks);
    std::cout << "last Two Weeks is: " << ctime(&tt);

    return 0;
}

答案 1 :(得分:1)

要扩展@ Jarod42的答案,如果你想获得自纪元开始(1970年1月1日)以来的时间戳(以毫秒为单位),请将以下两行附加到@ Jarod42的代码:

auto millis = std::chrono::duration_cast<std::chrono::milliseconds>\
                (lastTwoWeeks.time_since_epoch()).count();
std::cout << "Time stamp in milliseconds since UNIX epoch start: "\
          << millis << std::endl;