ctime(time library)是时间函数的库。
1 结构
typedef time_t long;
time_t是长整型,表示的是距(1970年,1月1日08:00:00)的秒数,常常通过time函数获得。
struct tm {
int tm_sec; //秒 0-59(一般)
int tm_min; //分 0-59
int tm_hour; //小时0-23
int tm_mday;//day 1-31
int tm_mon; //月0-11
int tm_year; //<span style="font-family:verdana,arial,helvetica,sans-serif"> 距 1900 的年数 如2013-1900 = 113</span>
int tm_wday; //星期 0-6
int tm_yday; //距1月1号天数,0-365
int tm_isdst; // 夏令时标识符。如果是夏令时,则为1;如果不是则为0;不明情况则为负。
}
tm包括日历日期和时间的各个组成
2 函数
time_t time ( time_t * timer );
//获取当前时间
time_t mktime ( struct tm * timeptr );//将struct tm转换为time_t
struct tm * localtime ( const time_t * timer ); //将time_t转换为struct tm
size_t strftime ( char * ptr, size_t maxsize, const char * format,
const struct tm * timeptr );
//将struct tm转换为特定格式的字符串输出
char *strptime(const char *buf,const char *format,struct tm *timeptr);
//将format形式的时间字符串转换为struct tm
3 常用
#include <ctime>
#include <iostream>
#include <time.h>
using namespace std;
int main() {
time_t now = time(NULL); // 获取当前时间
struct tm *nowtime = localtime(&now); // 把当前时间转换为tm的结构。
cout << nowtime->tm_mday;
time_t seconds;
seconds = mktime(nowtime);// 转换为time_t t
}
如何输出时间和输入时间。
#include <ctime>
#include <iostream>
#include <time.h>
#include <string>
using namespace std;
// strptime(<#const char *#>, <#const char *#>, <#struct tm *#>)
// strftime(<#char *#>, <#size_t#>, <#const char *#>, <#const struct tm *#>)
int main() {
time_t now = time(NULL);
struct tm *nowtime = localtime(&now);
cout << nowtime->tm_mday << endl;
char timestr[40]; // 一定要用c语言的字符串。
strftime(timestr, sizeof(timestr), "%Y-%m-%d-%H-%M-%S", nowtime);
// 把nowtime的内容按照"%Y-%m-%d-%H-%M-%S"的格式输入进timestr中;
cout << timestr << endl;
strptime("2013-02-07-11-23-05", "%Y-%m-%d-%H-%M-%S", nowtime);
// 把"2013-02-07-11-23-05"的内容按照"%Y-%m-%d-%H-%M-%S"输入进nowtime中;
cout << nowtime->tm_hour << endl;
return 0;
}
4 获取当前时间的毫秒
struct timeval{
time_t tv_sec; //秒 [long int]
suseconds_t tv_usec; //微秒 [long int]
};
#include <time.h>
#include <sys/time.h>
struct timeval tv;
// 常用于计算一个方法的响应时间。
gettimeofday (&tv, NULL);
uint64_t mseconds = tv.tv_sec * 1000 + tv.tv_usec / 1000;
5 表达转换。
#include <ctime>
#include <iostream>
#include <time.h>
#include <string>
#include <sys/time.h>
using namespace std;
int main() {
// difftime(<#time_t#>, <#time_t#>)
time_t now = time(NULL);
tm *fail = localtime(&now);
//gmtime(<#const time_t *#>);
// ctime(<#const time_t *#>);
//char * asctime(<#const struct tm *#>); 把tm转换为固定的时间表达形式。Tue Mar 8 19:49:01 2016
// ctime(<#const time_t *#>); 把time_t换砖为固定的时间表达形式。 Tue Mar 8 19:49:01 2016
cout << ctime(&now);
cout << asctime(fail);
return 0;
}