什么是时间戳?
- 时间戳是指格林威治时间自1970年1月1日(00:00:00 GTM)至当前时间的总秒数。它也被称为Unix时间戳(Unix Timestamp)。
- 时间戳是能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据,通常是一个字符序列,唯一地标识某一刻的时间
Demo
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
/*标准时间转换为时间戳*/
int standard_to_stamp(char *str_time)
{
struct tm stm;
int iY,iM,iD,iH,iMin,iS;
memset(&stm,0,sizeof(stm));
iY = atoi(str_time);
iM = atoi(str_time+5); //和实际输入的格式 有关系
iD = atoi(str_time+7);
iH = atoi(str_time+10);
iMin = atoi(str_time+13);
iS = atoi(str_time+16);
stm.tm_year=iY-1900;
stm.tm_mon=iM-1; // 月份从0开始,所以这里要减1
stm.tm_mday=iD;
stm.tm_hour=iH;
stm.tm_min=iMin;
stm.tm_sec=iS;
printf("解析后的时间是%d-%d-%d %d:%d:%d\n", iY, iM, iD, iH, iMin, iS);
return (int)mktime(&stm);
}
/*时间戳转换为标准时间*/
typedef struct times
{
int Year;
int Mon;
int Day;
int Hour;
int Min;
int Second;
}Times;
Times stamp_to_standard(int stampTime)
{
time_t tick = (time_t)stampTime;
struct tm tm;
char s[100];
Times standard;
tm = *localtime(&tick);
strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm);
printf("时间戳为:%d 转换成标准时间为: %s\n", (int)tick, s);
standard.Year = atoi(s);
standard.Mon = atoi(s+5);
standard.Day = atoi(s+8);
standard.Hour = atoi(s+11);
standard.Min = atoi(s+14);
standard.Second = atoi(s+17);
return standard;
}
int main(int argc, char **argv)
{
int a =0;
printf("输入的标准时间是: %s \n",argv[1]);
a=standard_to_stamp(argv[1]);
printf("标准时间转换为时间戳: %d\n",a);
stamp_to_standard(a);
return 0;
}
运行结果:
注意: 我们去网站上验证的时候,时间可能会自动加8,网站默认时间戳是UTC时间,然后会去自动同步成北京时间!!!
时间戳转换网站(会自动转成北京时间):https://tool.chinaz.com/tools/unixtime.aspx
时间戳转换网站(可转换不同时区的时间戳):https://tool.ip138.com/timestamp/