C++ 获取系统时间作为一天中的秒数

C++ Get System time as number of seconds in day

我正在编写一个程序来在用相机拍摄的图像上加上时间戳。为此,我使用 Windows 7 系统时间。我在下面的代码中使用了 GetSystemTimeAsFileTime()

FILETIME ft;
GetSystemTimeAsFileTime(&ft);
long long ll_now = (LONGLONG)ft.dwLowDateTime + ((LONGLONG)(ft.dwHighDateTime) << 32LL);

我想要做的是获取毫秒分辨率的一天中经过的秒数 (0- 86400),因此它将类似于 12345.678。这是正确的方法吗?如果是这样,我如何转换这个整数以获得当天过去的秒数?我将在字符串中显示时间并使用 fstream 将时间放入文本文件中。

谢谢

我不知道 Window APIC++ 标准库(C++11 起)可以这样使用:

#include <ctime>
#include <chrono>
#include <string>
#include <sstream>
#include <iomanip>

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