表示时间的三种类型

  1. 日历时间:从一个时间点到现在的秒数,用time_t表示
  2. 始终滴答时间:从进程启动到现在时钟的滴答数(每秒一般包含1000个)。用clock_t表示
  3. 分解时间:分解的数据结构如下。用tm表示

                              

【c】time.h_转换函数

 

从计算机里获得时间的方法

  1. tim_t time(time_t *time),从某一时间到现在的秒数,一般问1970年1月1日午夜
  2. clock_t clock(void),从进程启动到现在累计的始终滴答数
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
time_t times = time(NULL);
const clock_t clocks = clock();
cout << "times:" << times << endl;
cout << "clocks:" << clocks << endl;

cout << "-------------------" << endl;
const time_t times2 = time(×);
cout << "times2:" << times2 << endl;
}

结果

【c】time.h_ios_02

 

三种时间转换函数

  1. struct tm* gmtime(const time_t* time)
  2. struct tm* localtime(const time_t* time)
  3. time_t mktime(struct tm* ptm)

 

时间日期数据个格式化输出

  1. char* asctime(const struct tm* tmptr)  周几 月份数 日数 小时数:分钟数:秒钟数 年份数
  2. char* ctime(const time_t* time)  周几 月份数 日数 小时数:分钟数:秒钟数 年份数

对时间的操作

double difftime(time_t time2, time_t time1)

 

案例

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
const time_t t = time(NULL);
cout << "second from (1970.01.01:00:00)" << t << endl;
tm* current_time = localtime(&t);

cout << "year:" << 1900 + current_time->tm_year << endl;
cout << "month:" << 1 + current_time->tm_mon << endl;

cout << "=--------------=" << endl;
cout << "day of year:" << current_time->tm_yday << endl;
cout << "day of month:" << current_time->tm_mday << endl;
cout << "day of week:" << current_time->tm_wday << endl;
cout << "=--------------=" << endl;

cout << "hour:" << current_time->tm_hour << endl;
cout << "minute:" << current_time->tm_min << endl;
cout << "second:" << current_time->tm_sec << endl;
cout << "------------" << endl;
cout << "time:" << ctime(&t) << endl;
cout << "time:" << asctime(current_time) << endl;

}

结果

【c】time.h_ios_03

 

参考

time.h(维基)