1:头文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // sleep 函数头文件
#include <time.h> // 结构体time_t和函数time
#include <sys/time.h> // 结构体timeval和函数select,gettimeofday的头文件
2:取得当前时间 精确到秒 转换为日期形式
time_t nowT ; // time_t就是long int 类型
nowT = time(0); // 取得当前时间 ,秒级
// time(&nowT); // 取得当前时间 ,秒级
// nowT = time(NULL); // 取得当前时间 ,秒级
char strT[32];
/* 使用 strftime 将时间格式化成字符串("YYYY-MM-DD hh:mm:ss"格式)*/
strftime(strT, sizeof(strT), "%Y-%m-%d %H:%M:%S", localtime(&nowT));
printf("%s\n",strT);
strftime(strT, sizeof(strT), "%Y/%m/%d %H:%M:%S", localtime(&nowT));
printf("%s\n",strT);
3:取得当前时间 精确到微妙 转换为日期形式
/* 取得当前时间 精确到微妙 转换为日期形式 */
struct timeval nowTus;
// nowTus.tv_sec = 1; (秒)
// nowTus.tv_usec = 100000;(微妙)
gettimeofday( &nowTus, NULL ); // 取的当前时间秒数、 毫秒级
// struct tm* nowTm = localtime(&nowTus.tv_sec);
// localtime 将秒转换为年月日时分秒格式,为非线程安全函数
struct tm nowTm2; // localtime
localtime_r( &nowTus.tv_sec, &nowTm2 ); //localtime_r 为线程安全函数,建议使用。
char strT2[32];
snprintf(strT2, sizeof(strT2), "%04d/%02d/%02d %02d:%02d:%02d:%03dms",
nowTm2.tm_year + 1900, nowTm2.tm_mon + 1, nowTm2.tm_mday,
nowTm2.tm_hour, nowTm2.tm_min,nowTm2.tm_sec, nowTus.tv_usec / 1000);
printf("%s\n",strT2); // 方法 1
strftime(strT2, sizeof(strT2), "%Y-%m-%d %H:%M:%S", &nowTm2);
printf("%s:%03dms\n",strT2,nowTus.tv_usec / 1000); // 方法 2
4:将"YYYY-MM-DD hh:mm:ss"格式的时间转换为秒
char strT3[] = "2013/01/02 00:25:00";
struct tm nowTm3;
strptime(strT3,"%Y/%m/%d %H:%M:%S",&nowTm3); // 将"YYYY-MM-DD hh:mm:ss" 转换为tm
time_t longT = mktime(&nowTm3); // 将 tm 转换为1970年以来的秒
fprintf(stdout, "strT3=%s ,longT=%ld\n", strT3,(long)longT);
5:ctime 将时间转化为"Mon Nov 7 09:52:59 2016"形式
/*ctime 将时间转化为"Mon Nov 7 09:52:59 2016"形式,加上一个换行符共25个字符*/
time_t nowT4 = time(0); // 取得当前时间 ,秒级
char* pT = ctime(&nowT4);
char strT4[26];
memcpy(strT4, pT, 26);
printf("ctime time is: %s", strT4); // ctime 直接将秒转换成日期
struct tm nowTm4;
localtime_r( &nowT4, &nowTm4 );
printf("asctime time is: %s", asctime(&nowTm4)); // asctime把tm 的数据转换成字符串
6:sleep select使用
/* sleep select (设定等待时间,sleep线程内等待,select线程挂起节省CPU资源) */
sleep(1); // #include <unistd.h> 单位:秒
usleep(1000000); // #include <unistd.h> 单位:微妙
struct timeval wait_time;
wait_time.tv_sec = 1; //秒
wait_time.tv_usec = 100000; //微妙
// 在linux 内核2.6 以后的版本,select会清空最后一个参数的值
// 因此若在循环体使用select的话,必须每次都赋值
select(0, NULL, NULL, NULL, &wait_time); //使用select等待 ,10