將格式為 "YYYY-MM-DD HH:MM:SS.mmm" 的字符串轉換為自 1970-01-01 以來的毫秒數(int64)。
sscanf 解析年月日時分秒毫秒。CTime 對象(需 afx.h)。CTime::GetTime() 返回秒數(time_t),乘 1000 加上毫秒。
#include
#include // CString, CTime
using namespace std;
long long ChangeTimeStringToMilliseconds(CString strTime) {
char buf[100];
tm t = {}; int ms = 0;
// 解析:格式 "2014-11-4 21:39:01.234"
sscanf(strTime, "%[^\t]", buf, 100); // 讀取至 tab 或結束
sscanf(buf, "%d-%d-%d %d:%d:%d.%d",
&t.tm_year, &t.tm_mon, &t.tm_mday,
&t.tm_hour, &t.tm_min, &t.tm_sec, &ms);
// tm_year 從 1900 起算,tm_mon 1-12
if (t.tm_year >= 1900 && t.tm_mon >= 1 && t.tm_mon <= 12 &&
t.tm_mday >= 1 && t.tm_mday <= 31 &&
t.tm_hour >= 0 && t.tm_hour <= 23 &&
t.tm_min >= 0 && t.tm_min <= 59 &&
t.tm_sec >= 0 && t.tm_sec <= 59) {
CTime ct(t.tm_year, t.tm_mon, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec);
return ct.GetTime() * 1000LL + ms;
}
return 0;
}
int main() {
CString s = "2014-11-4 21:39:01.234";
long long ms = ChangeTimeStringToMilliseconds(s);
printf("%lld\n", ms); // 需用 %lld 或 %I64d
return 0;
}
std::chrono (C++20) 或 strptime (POSIX) 解析時間結構。date.h)。CTime 範圍:1970-01-01 至 2038-01-19 (32位 time_t) 或更大 (64位)。sscanf 格式串。INT64 在 VC++ 中為 __int64,打印用 %I64d。