如何在Windows系统下使用C++获取Windows epoch时间戳?
在Windows系统中用C++获取Windows epoch时间戳
Windows epoch时间指的是自1601年1月1日UTC起的100纳秒间隔数,Windows系统原生提供了API可以直接获取该时间戳,核心依赖FILETIME结构和相关系统函数。
方法一:获取UTC时间对应的Windows epoch
GetSystemTimeAsFileTime函数可以直接获取当前UTC时间的FILETIME结构,该结构存储的数值正是Windows epoch定义的100纳秒间隔数。只需将FILETIME转换为64位整数即可得到最终时间戳:
#include <windows.h> #include <iostream> int main() { FILETIME utc_file_time; // 获取当前UTC时间的FILETIME GetSystemTimeAsFileTime(&utc_file_time); // 将FILETIME的两个32位字段组合为64位整数 ULARGE_INTEGER ul_integer; ul_integer.LowPart = utc_file_time.dwLowDateTime; ul_integer.HighPart = utc_file_time.dwHighDateTime; unsigned long long windows_epoch_timestamp = ul_integer.QuadPart; std::cout << "UTC时间对应的Windows epoch时间戳(100纳秒间隔数):" << windows_epoch_timestamp << std::endl; return 0; }
方法二:获取本地时间对应的Windows epoch
如果需要基于本地时间而非UTC生成Windows epoch时间戳,可先通过GetLocalTime获取本地系统时间,再转换为FILETIME:
#include <windows.h> #include <iostream> int main() { SYSTEMTIME local_system_time; // 获取本地系统时间 GetLocalTime(&local_system_time); FILETIME local_file_time; // 将本地SYSTEMTIME转换为FILETIME SystemTimeToFileTime(&local_system_time, &local_file_time); // 转换为64位时间戳 ULARGE_INTEGER ul_integer; ul_integer.LowPart = local_file_time.dwLowDateTime; ul_integer.HighPart = local_file_time.dwHighDateTime; unsigned long long windows_epoch_local_timestamp = ul_integer.QuadPart; std::cout << "本地时间对应的Windows epoch时间戳(100纳秒间隔数):" << windows_epoch_local_timestamp << std::endl; return 0; }
关键说明
FILETIME结构由dwLowDateTime(低32位)和dwHighDateTime(高32位)两个字段组成,组合后是一个64位无符号整数,每一位代表100纳秒的间隔。- 使用
ULARGE_INTEGER是Windows平台下安全转换FILETIME到64位整数的标准方式,避免手动位运算可能出现的错误。
内容的提问来源于stack exchange,提问作者Massimo
相关产品推荐
相关产品推荐

