用c得到格式化的时间-实例

来源:互联网 发布:电脑网络连接不上 编辑:程序博客网 时间:2024/05/17 09:02
#include <stdio.h>#include <time.h>#include <errno.h>#include <string.h>#include <stdlib.h>#define MAX_BUFF_SIZE64char *get_formated_time(char *formate){time_t rawtime;struct tm * timeinfo = NULL;char timebuf[MAX_BUFF_SIZE] = {0};char *out_string = NULL;if ('\0' == formate[0] || NULL == formate){printf ("formate value error!\n");return NULL;}if (-1 == time (&rawtime)){printf ("time() error: %s\n", strerror(errno));return NULL;}timeinfo = localtime (&rawtime);if (NULL == timeinfo){printf ("localtime() error!\n");return NULL;}strftime (timebuf, MAX_BUFF_SIZE, formate, timeinfo);out_string = strdup (timebuf);return out_string;}int main(int argc, char *argv[]){    /* 要点:时间格式控制可通过man strftime查看 */char formate[] = "%Y-%m-%d %H:%M:%S";char *result_str = NULL;result_str = get_formated_time (formate);if (NULL != result_str){printf ("result_str=%s\n", result_str);}if (NULL != result_str){free (result_str);}return 0;}

0 0
原创粉丝点击