如何用c语言获取自1970年1月1日以来以毫秒为单位的UTCTime
题
有没有办法使用c语言中的time.h获取1970年以来的毫秒及其小数部分?
解决方案
这适用于 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执行看到 gettimeofday的窗户功能。
#include <sys/time.h>
...
struct timeval tp;
gettimeofday(&tp);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
这不是标准的C,但存在于两个的SysV和BSD衍生系统gettimeofday()
是,并且在POSIX。它返回时间,因为在一个struct timeval
划时代:
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
对于Unix和Linux,你可以使用 gettimeofday的。
对于Win32,您可以使用 GetSystemTimeAsFileTime 然后其转换为time_t的+毫秒。
// 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 的答案是正确的:你只要乘以1000 Unix时间戳获得毫秒
注意,通过依赖于Unix时间戳返回的所有毫秒值将是1000 倍数(如12345678000)。分辨率仍然只有1秒。
你不能得到小数部分的
这保尔的注释是正确的也。 Unix时间戳的不考虑闰秒即可。这使得甚至更少明智依靠转换为毫秒。
不隶属于 StackOverflow