1:函数说明
1.1 gettimeofday
#include <sys/time.h>
int gettimeofday(struct timeval*tv, struct timezone *tz);
其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果
下面是结构体的描述
struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
struct timezone{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime;/*DST 时间的修正方式*/
}
tv_sec是得到的秒数,是从 1900年1月 到 现在 之间有多少秒
1.2 localtime_r
#include <time.h>
struct tm *localtime_r(const time_t *timep, struct tm *result);
localtime_r是用来获取系统时间,运行于linux平台下
struct tm的结构为
int tm_sec; /* 秒 – 取值区间为[0,59] */
int tm_min; /* 分 - 取值区间为[0,59] */
int tm_hour; /* 时 - 取值区间为[0,23] */
int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */
int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */
int tm_year; /* 年份,其值等于实际年份减去1900 */
int tm_wday; /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */
int tm_yday; /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */
int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*
1.3 snprintf
int snprintf ( char * str, size_t size, const char * format, ... );
- str – 目标字符串。
- size – 拷贝字节数(Bytes)。
- format – 格式化成字符串。 .
- … – 可变参数。
设将可变参数(…)按照 format 格式化成字符串,并将字符串复制到 str 中,size 为要写入的字符的最大数目,超过 size 会被截断。
2:示例
/*************************************************************************
> File Name: snprintf.c
> Author: kayshi
> Mail: kayshi2019@qq.com
> Created Time: Fri 16 Oct 2020 03:19:56 PM CST
************************************************************************/
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
int main()
{
char buffer[50];
char buffer1[50];
char *s = "runppbcom";
struct timeval tv;
struct tm now_time;
int j = snprintf(buffer, 6, "%s\n", s);
printf("%s, %d\n", buffer, j);
gettimeofday(&tv, NULL);
printf("%ld\n", tv.tv_sec);
localtime_r(&tv.tv_sec, &now_time);
printf("%d-%d-%d %d-%d-%d\n", now_time.tm_year+1900, now_time.tm_mon+1, now_time.tm_mday, now_time.tm_hour, now_time.tm_min, now_time.tm_sec);
snprintf(buffer1, 60, "%d-%d-%d %d-%d-%d\n", now_time.tm_year+1900, now_time.tm_mon+1, now_time.tm_mday, now_time.tm_hour, now_time.tm_min, now_time.tm_sec);
printf("%s\n", buffer1);
}
结果
kayshi@ubuntu:~/code/Test$ ./a.out
runpp, 10
1602834778
2020-10-16 15-52-58
2020-10-16 15-52-58