C获取时间

方案1 优点:仅使用C标准库;缺点:只能精确到秒级 

#include <time.h> 
#include <stdio.h> 
int main( void ) 
{ 
    char tempstr[100];
    _strdate(tempstr);
    cout<<tempstr<<endl;

    time_t t = time( 0 ); 
    char tmp[64]; 
    strftime( tmp, sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z", localtime(&t) ); 
    cout<<tmp<<endl;

    char time[100];
    _strtime(time);
    cout<<time<<endl;
}

输出:
02/18/13
2013/02/18 16:21:07 Monday 本年第049天 中国标准时间
16:21:07

-------------------------------------------------------------------------------
方案2 优点:能精确到毫秒级;缺点:使用了windows API 

#include <windows.h> 
#include <stdio.h> 
int main( void ) 
{ 
     SYSTEMTIME sys; 
     GetLocalTime( &sys ); 
      printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d\n" 
                 ,sys.wYear,sys.wMonth,sys.wDay 
                 ,sys.wHour,sys.wMinute,sys.wSecond,sys.wMilliseconds 
                 ,sys.wDayOfWeek); 
      return 0;
}
输出:
2013/02/18 16:33:35.889 星期1

-------------------------------------------------------------------------------
方案3 优点:利用系统函数

#include<stdlib.h>
#include<iostream>
using namespace std;
void main(){
     system("time");
}

输出:

当前时间: 16:34:25.91

-------------------------------------------------------------------------------
方案4:

#include <stdio.h> 
#include <time.h> 
void main () 
{ 
    time_t rawtime; 
    struct tm * timeinfo; 
    time ( &rawtime ); 
    timeinfo = localtime ( &rawtime ); 
    printf ( "\007The current date/time is: %s", asctime (timeinfo) ); 
    printf( "%4d-%02d-%02d%02d-%02d-%02d\n",
         1900+timeinfo->tm_year,1+timeinfo->tm_mon,
         timeinfo->tm_mday,timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
}
输出:
The current date/time is: Mon Feb 18 16:35:33 2013
2013-02-1816-35-33

-------------------------------------------------------------------------------
方案5
VC中:

CTime CurrentTime=CTime::GetCurrentTime();
CString strTime;  

strTime.Format("%d:%d:%d",CurrentTime.GetHour(), CurrentTime.GetMinute(),CurrentTime.GetSecond());

-------------------------------------------------------------------------------
方案6:获得间隔时间:

#include <iostream.h>
#include <time.h>
int main(int argc[],char*args[]) 
{ 
    double tBegin = clock(); 
    cout<<"起始时间:"<<tBegin<<endl; 
    for(int i=0;i<100000000;i++)
    {
    }
    double tEnd = clock();
    cout<<"结束时间:"<<tEnd<<endl; 
    cout<<"耗时:"<<(tEnd - tBegin)/1000<<"秒!"<<endl; 
    return 0;
}
输出:
起始时间:1
结束时间:378
耗时:0.377秒!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值