C标准时间与时间戳的相互转换

什么是时间戳?

  • 时间戳是指格林威治时间自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/

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

行稳方能走远

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值