C语言实现字符转unix时间戳

来源:互联网 发布:java中replace函数 编辑:程序博客网 时间:2024/06/18 09:25

C语言实现字符转unix时间戳,需要先转成tm类型,再得到它的Unix时间戳。附上实现代码:

#include <stdio.h>#include <time.h>int strtotime(char datetime[]){struct tm tm_time;int unixtime;strptime(datetime, "%Y-%m-%d %H:%M:%S", &tm_time);unixtime = mktime(&tm_time);return unixtime;}

另附上几个时间相关的函数,做个笔记:

//当前时间

char* get_curr_time(){char* strtime = (char *)malloc(sizeof(char)*20);memset(strtime, 0, sizeof(char)*20);time_t now;time(&now);strftime(strtime, 20, "%Y-%m-%d %H:%M:%S", gmtime(&now));printf("Info: current time %s\n", strtime);return strtime;}

//当前时间的unix时间戳

int get_curr_unixtime(void){time_t now;int unixtime = time(&now);return unixtime;}

//字符转unix时间戳

int strtotime(char datetime[]){struct tm tm_time;int unixtime;strptime(datetime, “%Y-%m-%d %H:%M:%S”, &tm_time);unixtime = mktime(&tm_time);return unixtime;}

0 0
原创粉丝点击