2012-02-13 23:07:12|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:C/C++, 操作系统|来源:唯设编程网
在C/C++编程时,经常需要对时间/日期进行处理,在实际项目中经常需要获取当前系统时间,本文总结了几种常用的获取系统时间的方法,包含了C语言获取系统时间的方法,C++获取系统时间的方法和MFC环境获取系统时间的方法,读者可以根据实际需要选用。
方案— :使用C语言库获取系统当前时间
#include <time.h>
#include <stdio.h>
int main( void )
{
time_t t = time(0);
char tmp[64];
strftime(tmp, sizeof(tmp)
, "%Y/%m/%d %X %A 本年第%j天 %z"
,localtime(&t) );
puts( tmp );
return 0;
}
本方案的不足:只能精确到秒级
方案二 :使用C语言库函数GetLocalTime获取系统当前时间
#include <stdio.h>
int main( void )
{
SYSTEMTIME sys;
GetLocalTime( &sys );
printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d
"
,sys.wYear,sys.wMonth,sys.wDay
,sys.wHour,sys.wMinute,sys.wSecond,sys.wMilliseconds
,sys.wDayOfWeek);
return 0;
}
备注:本方案需要添加引用Windows API头文件的语句#include <windows.h>
方案三:使用C++的系统函数获取系统当前时间
#include<stdlib.h>
#include<iostream>
using namespace std;
void main(){
system("time");
}
备注:该方法可以改变电脑的时间设定
方案4:C++环境使用ctime库函数获取当前系统时间
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
time_t now_time;
now_time = time(NULL);
cout<<now_time;
return 0;
}
方案5:使用MFC的CTime类获取当前系统时间
CString CTestView::GetTime()
{
CTime CurrentTime=CTime::GetCurrentTime();
CString strTime;
strTime.Format("%d:%d:%d"
,CurrentTime.GetHour()
,CurrentTime.GetMinute()
,CurrentTime.GetSecond());
return strTime;
}
方案6:使用GetTickCount
//获取程序运行时间
long t1=GetTickCount();//程序段开始前取得系统运行时间(ms)
Sleep(500);
long t2=GetTickCount();();//程序段结束后取得系统运行时间(ms)
str.Format("time:%dms",t2-t1);//前后之差即 程序运行时间
AfxMessageBox(str);
//获取系统运行时间
long t=GetTickCount();
CString str,str1;
str1.Format("系统已运行 %d时",t/3600000);
str=str1;
t%=3600000;
str1.Format("%d分",t/60000);
str+=str1;
t%=60000;
str1.Format("%d秒",t/1000);
str+=str1;
AfxMessageBox(str);