c++ - 如何从 C++ 中的当前日期返回两周以毫秒为单位的时间戳?

标签 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;
}

最佳答案

对于 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;
}

关于c++ - 如何从 C++ 中的当前日期返回两周以毫秒为单位的时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25150213/

相关文章:

c++ - 用数组进行字节交换?

c++ - 将链表转换为二叉搜索树,执行操作并将树作为列表返回

c++ - 解决链接器错误 : undefined reference to static class members

javascript - 时间戳不一致

ios - 如何按时间顺序对 Firebase 数据库进行排序?

ffmpeg - 如何在 FFmpeg 的 drawText 中使用毫秒?

android - SimpleDateFormat 表示还有 2 小时

c++ - 以下代码不起作用

mysql - 我可以为 MySQL 中的每条记录获取唯一的 TIMESTAMP

javascript - 在 JavaScript 中将 UTC 毫秒转换为中部时间