一直想防着redis写个类似功能的,可惜c太渣,于是今天开始从基本抓起-时间函数
根据多年写业务的经验,通常利用到的时间函数有:
获取当前时间戳 current_time()
获取当前微秒(需要高精度时间场景) micro_time()
将字符串时间转换成时间戳 strtotime()
将 时间戳按照指定格式生成字符串 date()
百度了下c语言自带的常用时间函数有:
1. time_t time(time_t * timer) : 获取当前时间戳,其中 time_t定义如下:
typedef long time_t;
2. char *strptime(const char *buf,const char*format,struct tm *timeptr)
将时间格式为format的buf字符串转换成tm时间格式,tm 结构如下:
struct tm {
int tm_sec; //second [0,59]
int tm_min; //minute [0,59]
int tm_hour; //hour [0,23]
int tm_mday; //day [1,31]
int tm_mon; //month [0,11]
int tm_year; //year -1900
int tm_wday; //weekday 星期几
int tm_yday; //yearday 年积日
int tm_isdst; //
};
3. time_t mktime(strcut tm * timeptr) 将时间数据结构转换为时间戳
4. size_t strftime(char *str, size_t count, const char *format, const struct tm *tm); 将时间格式转为指定格式的字符串str
5. struct tm *localtime(const time_t * calptr); 将时间戳转换为本地时间格式
利用以上五个函数即可实现常用的四个目标函数,代码如下:
/*************************************************************************
> File Name: time.c
> Author:
> Mail:
> Created Time: Wed 28 Mar 2018 06:20:59 PM CST
************************************************************************/
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
/*
struct tm {
int tm_sec; //second [0,59]
int tm_min; //minute [0,59]
int tm_hour; //hour [0,23]
int tm_mday; //day [1,31]
int tm_mon; //month [0,11]
int tm_year; //year -1900
int tm_wday; //weekday
int tm_yday; //yearday
int tm_isdst; //
};
*/
typedef time_t int_time;
typedef double float_time;
typedef char * str_time;
typedef const char const_str_time[100];
int_time current_time();
int_time strtotime(str_time strTime);
str_time date(const_str_time format ,int_time intTime);
float_time micro_time();
int main(void) {
printf("%d\n",strtotime("2014-12-12 12:12:12"));
printf("%s\n",date("%Y/%m/%d %H:%M:%S",strtotime("2014-12-12 12:12:12")));
printf("%d\n",current_time());
printf("%f\n",micro_time());
}
/*
get current time with time stamp format
获取当前时间戳
*/
int_time current_time() {
return time(NULL);
}
/*
get current time with micro time stamp format
获取当前微秒时间戳
*/
float_time micro_time() {
struct {int_time sec; int_time micro;} microTime;
gettimeofday( µTime, NULL );
return microTime.sec + microTime.micro/1000000.0;
}
/*
change string format to time_stamp format
将时间戳格式转换成指定格式字符串
@example : strtotime("2018-03-12 12:23:11")
*/
int_time strtotime(str_time strTime) {
struct tm stm;
strptime(strTime, "%Y-%m-%d %H:%M:%S",&stm);
int_time intTime = mktime(&stm);
return intTime;
}
/*
change time_stamp format to string format
将时间戳格式转换成指定格式字符串
*/
str_time date(const_str_time format ,int_time intTime) {
struct tm *tmTime;
str_time strTime;
tmTime = localtime(&intTime);
strftime(strTime,100,format,tmTime);
return strTime;
}