将时间字符串转化成毫秒形式的时间

  前两天遇到一个要将字符串形式的时间转化成用毫秒表示的时间,作为一个初学者的我一下子没有了头绪,所以只能各种搜索。终于实现了自己想要的结果。先上代码,如果有不对的地方,希望大家指正。

 1 #include <iostream>
 2 #include <afx.h> //在非MFC下,使用CString需要包含这个头文件
 3 using namespace std;
 4 
 5 INT64 ChangeTimeStringToMillisconds(CString strTime);
 6 INT64 ChangeTimeSpanStringToMillisconds(CString strTime);
 7 
 8 void main()
 9 {
10     CString strTime = "2014-11-4 21:39:01.234";
11     CString strTimeSpan = "00:00:10.001";
12     INT64 nTime = ChangeTimeStringToMillisconds(strTime);
13     INT64 nTimeSpan = ChangeTimeSpanStringToMillisconds(strTimeSpan);
14     //cout << miao << endl; //<<操作符没有被INT64重载 error C2593: 'operator <<' is ambiguous
15     printf("Time String Change To Milliscond = %I64d\n", nTime);
16     printf("TimeSpan String Change To Milliscond = %I64d\n", nTimeSpan);
17 }
18 
19 INT64 ChangeTimeStringToMillisconds(CString strTime)
20 {
21     char buf[100];
22     tm t;
23     int nms = 0;
24     memset(&t, 0, sizeof(tm));
25     sscanf(strTime, _T("%[^\t]"), buf, 100);
26     sscanf(buf, _T("%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, &nms);
27     if ((t.tm_year >= 1900)
28         && (t.tm_mon >= 1 && t.tm_mon <= 12)
29         && (t.tm_mday >= 1 && t.tm_mday <= 31)
30         && (t.tm_hour >= 0 && t.tm_hour <= 59)
31         && (t.tm_min >= 0 && t.tm_min <= 59)
32         && (t.tm_sec >= 0 && t.tm_sec <= 59))
33     {
34         CTime time(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
35         INT64 nmstime = time.GetTime() * 1000 + nms; //time.GetTime()得到的结果是秒
36         return nmstime;
37     }
38     return 0;
39 }
40 
41 INT64 ChangeTimeSpanStringToMillisconds(CString strTime)
42 {
43     char buf[100];
44     int nHours = 0, nMins = 0, nSecs = 0, nMs = 0; //时分秒和毫秒
45     sscanf(strTime, _T("%[^\t]"), buf, 100);
46     sscanf(buf, _T("%d:%d:%d.%d"), &nHours, &nMins, &nSecs, &nMs);
47     if ((nHours >= 0 && nHours <= 23)
48         && (nMins >= 0 && nMins <= 59)
49         && (nSecs >= 0 && nSecs <= 59))
50     {
51         CTimeSpan timespan(0, nHours, nMins, nSecs);
52         INT64 nmstimespan = timespan.GetTotalSeconds() * 1000 + nMs;
53         return nmstimespan;
54     }
55     return 0;
56 }

 

posted @ 2014-11-12 22:01  情敌贝多芬  阅读(2708)  评论(0)    收藏  举报