时间戳与时间字符串之间的转换
时间戳便于存储,而时间字符串能直观地显示当前的时间。有时候,我们需要时间戳与时间字符串之间的转换。
代码实现
//time_binary_string_convert.h
#ifndef _TIME_BINARY_STRING_CONVERT_H_
#define _TIME_BINARY_STRING_CONVERT_H_
#include <time.h>
//函数声明
//时间戳转换成时间字符串
char *time_binary2string(time_t binary_time, char *pstring_time);
//时间字符串转换成时间戳
time_t time_string2binary(char *pstring_time);
#endif
//time_binary_string_convert.c
#include "time_binary_string_convert.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
//函数定义(函数实现)
char *time_binary2string(time_t binary_time, char *pstring_time)
{
if(NULL == pstring_time)
return NULL;
struct tm when;
time(&binary_time);
when = *localtime(&binary_time);
sprintf(pstring_time, "%04d-%02d-%02d %02d:%02d:%02d",
when.tm_year+1900, when.tm_mon+1, when.tm_mday,
when.tm_hour, when.tm_min, when.tm_sec);
return pstring_time;
}
time_t time_string2binary(char *pstring_time)
{
time_t retime;
struct tm when;
unsigned char time_string[20] = {0};
unsigned char year_str[5]={0}, month_str[5]={0}, day_str[5]={0},
hour_str[5]={0}, min_str[5]={0}, sec_str[5]={0};
memcpy(time_string, pstring_time, 20);
memcpy(year_str, time_string, 4);
memcpy(month_str, time_string+5, 2);
memcpy(day_str, time_string+8, 2);
memcpy(hour_str, time_string+11, 2);
memcpy(min_str, time_string+14, 2);
memcpy(sec_str, time_string+17, 2);
when.tm_year = atoi(year_str)-1900;
when.tm_mon = atoi(month_str)-1;
when.tm_mday = atoi(day_str);
when.tm_hour = atoi(hour_str);
when.tm_min = atoi(min_str);
when.tm_sec = atoi(sec_str);
retime = mktime(&when)-(60*60*8);
return retime;
}
//test.c
#include "time_binary_string_convert.h"
#include <stdio.h>
int main(int argc, char *argv[])
{
char time_buf[20] = {0};
char *ptime = NULL;
time_t now = 0;
time_t binary_time = 0;
ptime = time_binary2string(now, time_buf);
printf("binary2string() time_buf: %s, ptime: %s\n", time_buf, ptime);
binary_time = time_string2binary(time_buf);
printf("string2binary() binary_time = %ld\n", binary_time);
return 0;
}
相关代码已通过调试。