C++获取系统时间,以一天中的秒数表示

k97glaaz  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(116)

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

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

我想做的是计算一天中所花的秒数(0- 86400),因此它将是类似于12345.678的值。这是正确的方法吗?如果是,我如何转换这个整数来得到当天所经过的秒数?我将在字符串中显示时间,并使用fstream将时间放入文本文件中。
谢谢

oyjwcjzk

oyjwcjzk1#

我不知道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

相关问题