有什么方法可以使用 c 语言中的 time.h 从 1970 年获取毫秒及其小数部分?
6 回答
这适用于 Ubuntu Linux:
#include <sys/time.h>
...
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned long long millisecondsSinceEpoch =
(unsigned long long)(tv.tv_sec) * 1000 +
(unsigned long long)(tv.tv_usec) / 1000;
printf("%llu\n", millisecondsSinceEpoch);
在撰写本文时,上面的 printf() 给了我 1338850197035。您可以在TimestampConvert.com网站上进行完整性检查,您可以在其中输入值以取回等效的人类可读时间(尽管没有毫秒精度) .
如果你想要毫秒分辨率,你可以在 Posix 中使用 gettimeofday() 。对于 Windows 实现,请参阅 Windows 的gettimeofday 函数。
#include <sys/time.h>
...
struct timeval tp;
gettimeofday(&tp);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
它不是标准的 C,但gettimeofday()
存在于 SysV 和 BSD 派生系统中,并且存在于 POSIX 中。它返回自 a 中的纪元以来的时间struct timeval
:
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
对于 Unix 和 Linux,您可以使用gettimeofday。
对于 Win32,您可以使用GetSystemTimeAsFileTime,然后将其转换为 time_t + 毫秒:
void FileTimeToUnixTime(FILETIME ft, time_t* t, int* ms)
{
LONGLONG ll = ft.dwLowDateTime | (static_cast<LONGLONG>(ft.dwHighDateTime) << 32);
ll -= 116444736000000000;
*ms = (ll % 10000000) / 10000;
ll /= 10000000;
*t = static_cast<time_t>(ll);
}
// the system time
SYSTEMTIME systemTime;
GetSystemTime( &systemTime );
// the current file time
FILETIME fileTime;
SystemTimeToFileTime( &systemTime, &fileTime );
// filetime in 100 nanosecond resolution
ULONGLONG fileTimeNano100;
fileTimeNano100 = (((ULONGLONG) fileTime.dwHighDateTime) << 32) + fileTime.dwLowDateTime;
//to milliseconds and unix windows epoche offset removed
ULONGLONG posixTime = fileTimeNano100/10000 - 11644473600000;
return posixTime;
Unix时间或Posix时间是自您提到的纪元以来的秒数。
bzabhi的回答是正确的:您只需将 Unix 时间戳乘以 1000 即可得到毫秒。
请注意,依赖 Unix 时间戳返回的所有毫秒值都是 1000 的倍数(例如 12345678000)。分辨率仍然只有1秒。
你不能得到分数部分
帕维尔的评论也是正确的。Unix 时间戳不考虑闰秒。这使得依赖于毫秒的转换变得更加不明智。