现在的位置: 首页 > 综合 > 正文

时间函数汇总

2013年10月09日 ⁄ 综合 ⁄ 共 2546字 ⁄ 字号 评论关闭

程序中用到与时间相关的函数时,需要在程序的头部加入头文件:#include<time.h>

===================>>有关时间的结构如下<<========
1.time_t

long            time_t; /* time of day in seconds */

2.tm

struct  tm { 

     int   tm_sec;    /* seconds after the minute - [0, 59] */
     int   tm_min;    /* minutes after the hour - [0, 59] */
     int   tm_hour;   /* hour since midnight - [0, 23] */
     int   tm_mday;   /* day of the month - [1, 31] */
     int   tm_mon;    /* months since January - [0, 11] */
     int   tm_year;   /* years since 1900 */
     int   tm_wday;   /* days since Sunday - [0, 6] */
     int   tm_yday;   /* days since January 1 - [0, 365] */
     int   tm_isdst;
};

====================>>有关时间的函数<<============

-------------------time------------------------------------------
功能:返回从公元1970年1月1日0时0分0秒到现在所经过的秒数。如果t并非空指针的话,此函数也会将返回值存到t指针所指的内存。
原型:time_t time( time_t *t)
示例:
#include<iostream>
#include<time.h>
using namespace std;

int  main(){

        time_t current;
        time_t *currPtr = &current;
        time(currPtr);
        cout << current << endl;
        return 0;
}

 

------------------------localtime------------------------------
功能:将time_t类型的时间值放入到tm结构的不同字段中
原型:struct tm* localtime( const time_t * time)
示例:
#include<time.h>
#include<iostream>
using namespace std;

int main()
{
 time_t timeTmp;     //定义一个时间变量
 struct tm* timeNow;     //定义一个指向tm结构体的指针timeNow
 time(&timeTmp);      //调用时间函数time_t time( time_t *t)
 timeNow = localtime(&timeTmp);       //调用struct tm* localtime( const time_t * time)获得当前时间  

 cout << "current year====>" << timeNow->tm_year+1900 << endl;    //tm_year从1990年开始加上1990年
 cout << "current month====>" << timeNow->tm_mon+1 << endl;    //从[0-11]定义的所以需要加1
 cout << "current day====>" << timeNow->tm_mday << endl;        
 return 0;
}

 

--------------------asctime------------------------------------
功能:将tm结构中的时间转换为字符串。此函数已经由时区转换成当地时间,字符串格式为:“Wed Jun 30 21:49:08 1993\n”
原型:char* asctime( const struct tm *time)
示例:

#include<time.h>
#include<iostream>
using namespace std;

int main()
{
 time_t timeTmp;   //定义一个时间变量
 struct tm* timeNow;    //定义一个指向tm结构体的指针timeNow
 time(&timeTmp);          //调用时间函数time_t time( time_t *t)
 timeNow = localtime(&timeTmp);      //调用struct tm* localtime( const time_t * time)获得当前时间    

 cout << "current year====>" << timeNow->tm_year+1900 << endl;
 cout << "current month====>" << timeNow->tm_mon+1 << endl;
 cout << "current day====>" << timeNow->tm_mday << endl;

 cout << "current time======>" << asctime(timeNow) << endl;  //调用char* asctime( const struct tm *time)将tm结构中的时间转换为字符串。
 //此函数已经由时区转换成当地时间
 return 0;

}

 

-------------------ctime-------------------------------------------
功能:将time_t类型的时间转换为字符串。
原型:char* ctime( const time_t *time)
示例:

#include<time.h>
#include<iostream>
using namespace std;

int main()
{
 time_t timeTmp;
 time(&timeTmp);
 cout << "current time is====>" << ctime( &timeTmp ) << endl;
 return 0;
}

抱歉!评论已关闭.