将本地时间转换为时间戳

时间:2021-10-01 02:04:30

How would it be to convert a SYSTEMTIME structure returned by GetLocalTime to time stamp ( seconds since 1970, ULONG )?

如何将GetLocalTime返回的SYSTEMTIME结构转换为时间戳(自1970年以来的秒数,ULONG)?

1 个解决方案

#1


2  

One way is to convert both the reference time and the target time to FILETIME structures, which then lets you perform simple arithmetic upon their values. These are measured in 100ns units and so you need to divide the final result by 10000000 to get number of seconds.

一种方法是将参考时间和目标时间都转换为FILETIME结构,然后可以对其值执行简单的算术运算。这些以100ns为单位进行测量,因此您需要将最终结果除以10000000以获得秒数。

// reference time, convert to FILETIME
SYSTEMTIME stRef{};
stRef.wYear = 1970;
stRef.wMonth = 1;
stRef.wDay = 1;

FILETIME ftRef;
SystemTimeToFileTime(&stRef, &ftRef);


// target time, convert to FILETIME
SYSTEMTIME stTarget;
GetLocalTime(&stTarget);

FILETIME ftTarget;
SystemTimeToFileTime(&stTarget, &ftTarget);


// convert both to ULARGE_INTEGER
ULARGE_INTEGER ulRef, ulTarget;
ulRef.HighPart = ftRef.dwHighDateTime;
ulRef.LowPart = ftRef.dwLowDateTime;
ulTarget.HighPart = ftTarget.dwHighDateTime;
ulTarget.LowPart = ftTarget.dwLowDateTime;


// subtract reference time from target time
ulTarget.QuadPart -= ulRef.QuadPart;

// convert to seconds (divide by 10000000)
DWORD dwSecondsSinceRefTime = ulTarget.QuadPart / 10000000i64;

#1


2  

One way is to convert both the reference time and the target time to FILETIME structures, which then lets you perform simple arithmetic upon their values. These are measured in 100ns units and so you need to divide the final result by 10000000 to get number of seconds.

一种方法是将参考时间和目标时间都转换为FILETIME结构,然后可以对其值执行简单的算术运算。这些以100ns为单位进行测量,因此您需要将最终结果除以10000000以获得秒数。

// reference time, convert to FILETIME
SYSTEMTIME stRef{};
stRef.wYear = 1970;
stRef.wMonth = 1;
stRef.wDay = 1;

FILETIME ftRef;
SystemTimeToFileTime(&stRef, &ftRef);


// target time, convert to FILETIME
SYSTEMTIME stTarget;
GetLocalTime(&stTarget);

FILETIME ftTarget;
SystemTimeToFileTime(&stTarget, &ftTarget);


// convert both to ULARGE_INTEGER
ULARGE_INTEGER ulRef, ulTarget;
ulRef.HighPart = ftRef.dwHighDateTime;
ulRef.LowPart = ftRef.dwLowDateTime;
ulTarget.HighPart = ftTarget.dwHighDateTime;
ulTarget.LowPart = ftTarget.dwLowDateTime;


// subtract reference time from target time
ulTarget.QuadPart -= ulRef.QuadPart;

// convert to seconds (divide by 10000000)
DWORD dwSecondsSinceRefTime = ulTarget.QuadPart / 10000000i64;