准备回家了,闲来无时想同步一下机器的时间,写了一小段代码,有点意思!放上来玩玩!程序主要使用了MFC Wininet包装类,和几个时间操作API。
运行后可以同步电脑和google的时间,我觉得google服务器的时间应该是很准的吧!也许吧!
void SyncTime(void)
{
static CInternetSession Session;
CString strRequest(_T("http://www.google.com/"));
TRY
{
CHttpFile *pHttpFile=(CHttpFile*)Session.OpenURL(strRequest);
SYSTEMTIME stm={0};
if(pHttpFile->QueryInfo(HTTP_QUERY_DATE,&stm))
{
SetSystemTime(&stm);
SYSTEMTIME stmLocal=stm;
//先将UTC时间转成本地时间
FILETIME ftmUtc={0};
SystemTimeToFileTime(&stmLocal,&ftmUtc);
FILETIME ftmLocal={0};
FileTimeToLocalFileTime(&ftmUtc,&ftmLocal);
FileTimeToSystemTime(&ftmLocal,&stmLocal);
//再显示出来
CTime tmLocal(stmLocal);
CTime tmUTC(stm);
cout<<"Synchronization system time with google completed!"<<endl;
cout<<(LPCTSTR)tmUTC.Format(_T("UTC Time,%Y %B %d,%A, %H:%M:%S"))<<endl;
cout<<(LPCTSTR)tmLocal.Format(_T("%Z,%Y %B %d,%A, %H:%M:%S"))<<endl;
}
pHttpFile->Close();
}
CATCH(CInternetException,e)
{
e->ReportError();
e->Delete();
}
END_CATCH
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
SyncTime();
}
return nRetCode;
}
运行结果:
Synchronization system time with google completed!
UTC Time,2006 September 27,Wednesday, 09:16:15
China Standard Time,2006 September 27,Wednesday, 17:16:15
【作者: kruglinski】【访问统计:】【2006年09月27日 星期三 17:13】【 加入博采】【打印】
你可以使用这个链接引用该篇文章 http://publishblog.blogchina.com/blog/tb.b?diaryID=5700893
- 评论人:anonymous
2006-10-26 18:12:47
|
||||
一直不知道,这样能得到服务器时间,领教了。呵呵 |
||||
- 评论人:anonymous
2006-09-29 17:02:37
|
||||
那好土啊,程序员要把代码延伸生活的各个角落,哈哈哈 |
||||
- 评论人:417
2006-09-28 14:06:36
|
||||
在任务栏,时间显示上双击,选择时间,嘿嘿,里面有时间同步啊,不过好像只有在下才有这个功能。 |
||||