我正在编写一个程序,将时间戳放在相机拍摄的图像上。为了做到这一点,我使用的是Windows 7系统时间。我在下面的代码中使用了GetSystemTimeAsFileTime()
:
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
long long ll_now = (LONGLONG)ft.dwLowDateTime + ((LONGLONG)(ft.dwHighDateTime) << 32LL);
我想做的是用毫秒分辨率获得一天中(0- 86400)的秒数,所以它将是12345.678。这是正确的做法吗?如果是这样,我如何转换这个整数,以获得秒数在当前的一天?我将在字符串中显示时间,并使用fstream
将时间放在文本文件中。
谢谢
我不知道Window API
,但C++
标准库(自c++ 11)可以这样使用:
#include <ctime>
#include <chrono>
#include <string>
#include <sstream>
#include <iomanip>
#include <iostream>
std::string stamp_secs_dot_ms()
{
using namespace std::chrono;
auto now = system_clock::now();
// tt stores time in seconds since epoch
std::time_t tt = system_clock::to_time_t(now);
// broken time as of now
std::tm bt = *std::localtime(&tt);
// alter broken time to the beginning of today
bt.tm_hour = 0;
bt.tm_min = 0;
bt.tm_sec = 0;
// convert broken time back into std::time_t
tt = std::mktime(&bt);
// start of today in system_clock units
auto start_of_today = system_clock::from_time_t(tt);
// today's duration in system clock units
auto length_of_today = now - start_of_today;
// seconds since start of today
seconds secs = duration_cast<seconds>(length_of_today); // whole seconds
// milliseconds since start of today
milliseconds ms = duration_cast<milliseconds>(length_of_today);
// subtract the number of seconds from the number of milliseconds
// to get the current millisecond
ms -= secs;
// build output string
std::ostringstream oss;
oss.fill('0');
oss << std::setw(5) << secs.count();
oss << '.' << std::setw(3) << ms.count();
return oss.str();
}
int main()
{
std::cout << stamp_secs_dot_ms() << 'n';
}
示例输出:
13641.509