以下博文转载自:
https://www.cnblogs.com/starf/p/3668586.html
https://www.cnblogs.com/long5683/p/9999746.html
方式一
#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) );
exit(0);
}
================================================
#include <time.h> -- 必须时间函数头文件
time_t -- 时间类型(time.h 定义)
struct tm -- 时间结构time.h 定义下:
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
time ( &rawtime ); -- 获取时间秒计从1970年1月日起算存于rawtime
localtime ( &rawtime ); -- 转当地时间tm 时间结构
asctime ()-- 转标准ASCII时间格式:
星期 月 日 时:分:秒 年
================================================
要格式样输出:
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);
直接打印tmtm_year 从1900年计算所要加1900
月tm_mon从0计算所要加1
输出到某个字符串:
//获取当地时间
char now_date[16]={'\0'};
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
snprintf(now_date,16,"%04d-%02d-%02d",(1900+timeinfo->tm_year),(1+timeinfo->tm_mon),
timeinfo->tm_mday);
printf("Current date:%s\n",now_date);
方式二
================================================
gettimeofday获取时间和时区,获取的为1970/1/1到现在时间的秒数,精确到微秒
gettimeofday(struct timeval *tv, struct timezone *tz)函数
功能:获取当前精确时间(Unix时间)
其中:
timeval为时间
truct timeval{
long tv_sec; // 秒数
long tv_usec; // 微秒数
}
timezone为时区
struct timezone{
int tz_minuteswest;/*和greenwich 时间差了多少分钟*/
int tz_dsttime;/*type of DST correction*/
}
在gettimeofday()函数中tv或者tz都可以为空。如果为空则就不返回其对应的结构体。
函数执行成功后返回0,失败后返回-1,错误代码存于errno中
================================================
#include<stdio.h>
#include<sys/time.h>
int main(){
struct timeval tv;
gettimeofday(&tv,NULL);
printf("%d,%d\n",tv.tv_sec,tv.tv_usec);
return 0;
}