获取系统时间作为一天中的秒数
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 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
相关文章:
- C++ Chrono 确定一天是否是周末?
- 编写了一个C++代码来检查表达式是否具有平衡括号并且我的代码未运行.我已经卡了一天了
- 我正在尝试制作一个程序,在添加 n 天(整数)后告诉一个人什么是一天(例如星期一等)
- std::get_time 没有解析一天
- 以秒为单位将时间从纪元转换为一年中的某一天?
- 解决一年中的一天 c++
- Strftime在iOS上返回一周中不正确的一天
- 一个月的最后一天?
- 泽勒全等编码,输出错误的一天
- C++计算一周中未来的一天
- C++输入日期获取哪一天
- 如何从structtm中减去一天,同时确保完整性
- 跨平台获取一天中的时间的方式
- 30天 系统时间的差异
- 从日期开始计算一年中的某一天
- 将某个时间增加一天
- 我如何将一年中的某一天(1-365)转换为其等效日期(即2013年1月5日)C++
- C或C++代码,使用时区从epoch时间戳中获取一天中的小时数
- 如何用重载函数对一天中的时间进行乘除,例如10:00和5:00
- 获取系统时间作为一天中的秒数