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
- str – 目标字元串。
- size – 拷貝位元組數(Bytes)。
- format – 格式化成字元串。 .
- … – 可變參數。
設将可變參數(…)按照 format 格式化成字元串,并将字元串複制到 str 中,size 為要寫入的字元的最大數目,超過 size 會被截斷。
2:示例
/*************************************************************************
> File Name: snprintf.c
> Author: kayshi
> Mail: [email protected]
> 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);
}
結果
[email protected]:~/code/Test$ ./a.out
runpp, 10
1602834778
2020-10-16 15-52-58
2020-10-16 15-52-58