<C语言>“获取时间”函数的定义与封装

来源:互联网 发布:域名证书提供商 编辑:程序博客网 时间:2024/05/20 07:18

C语言获取本地时间,有时候需要不同的格式来表示,作者自己编写了一个头文件,封装了日期和时间,便于调用,在这里分享给大家:

/*  The function for geting date. *//*author:wsgdate:2017/09/08version:1 */#ifndef _GETTM_H_#define _GETTM_H_/* head file */#include <time.h>/* macro */#define SIZE 30/* Declaration of function *//* include:struct tm *get_loc_time(void);int get_loc_year(void);int get_loc_mon(void);int get_loc_mday(void);char *get_loc_wday(void);int get_loc_hour(void);int get_loc_min(void);int get_loc_sec(void); void get_str_time(char buf[]);*end here*//* Function encapsulation */struct tm *get_loc_time(void){  time_t t;  time(&t);    struct tm *loc_time;  loc_time = localtime(&t);    return loc_time;}/* get date:include year_mon_mday and wday and hour_min_sec *///get date yearint get_loc_year(void){struct tm *loc_time = get_loc_time();return ( (loc_time->tm_year)+1900 );}//get date monint get_loc_mon(void){struct tm *loc_time = get_loc_time();return ( (loc_time->tm_mon)+1 );}//get date mdayint get_loc_mday(void){struct tm *loc_time = get_loc_time();return ( (loc_time->tm_mday) );}//get date wdaychar *get_loc_wday(void){char *wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};struct tm *loc_time = get_loc_time();return ( wday[(loc_time->tm_wday)] );}// get date hourint get_loc_hour(void){struct tm *loc_time = get_loc_time();return ( (loc_time->tm_hour) );}// get date minint get_loc_min(void){struct tm *loc_time = get_loc_time();return ( (loc_time->tm_min) );}// get date secint get_loc_sec(void){struct tm *loc_time = get_loc_time();return ( (loc_time->tm_sec) );}//change date to formate stringvoid get_str_time(char buf[]){int year, mon, mday, hour, min, sec;;char *wday = NULL;year = get_loc_year();mon = get_loc_mon();mday = get_loc_mday();wday = get_loc_wday();hour = get_loc_hour();min = get_loc_min();sec = get_loc_sec();/* change any format to string */snprintf(buf, SIZE, "%d/%02d/%02d %s %02d:%02d:%02d\n", year, mon, mday, wday, hour, min, sec);}#endif


test:

#include <stdio.h>#include "gettm.h"int main(void){int year, mon, mday;char *wday = NULL;int hour, min, sec;year = get_loc_year();mon = get_loc_mon();mday = get_loc_mday();wday = get_loc_wday();hour = get_loc_hour();min = get_loc_min();sec = get_loc_sec(); printf("%d/%02d/%02d ", year, mon, mday);printf("%s ", wday);printf("%02d:%02d:%02d\n", hour, min, sec); char buf[SIZE] = {};get_str_time(buf);printf("%s", buf);return 0;}

You can see the result:

2017/09/08 Fri 11:02:34
2017/09/08 Fri 11:02:34


点此:C/C++关于日期和时间的函数大全

原创粉丝点击