我需要计算当前日期两周前日期的时间戳(以毫秒为单位)。
到目前为止,这是我以毫秒为单位计算当前时间戳的方式 -
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/