C语言标准时间转时间戳

标准时间转时间戳

1.思路

	1.1 计算当前年过去的年份中有多少闰年
	1.2 单独计算当前年有多少天
	1.3 统计总共的天数
	1.4 计算所有时间

2.小插曲

计算出来的时间需要减去8小时的时差,估计是以1970年8点开始计算时间的

3.代码实现

#include <stdio.h>
#include "stdio.h"
#include "stdbool.h"

typedef struct
{
	int 	year;
	int 	month;
	int 	day;
	int 	hour;
	int 	min;
	int 	sec;
	int 	ms;
}_clock;

_clock clock = 
{
	1972,
	10,
	8,
	17,
	14,
	11,
	222
};

void timToStamp(long long int *pStamp, _clock clock)
{
	static  int MON1[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};	//平年
	static  int MON2[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};	//闰年
	int *month = NULL;
	int leapYearCnt = 0;
	long long int days = 0;
	//获得1970年到当前年的前一年共有多少闰天
	for(int i = 1970; i < clock.year; i++)
	{
		if((i % 4 == 0 && i % 100 != 0) || (i % 400 == 0))
		{
			leapYearCnt++;
		}
	}
	days = leapYearCnt * 366 + (clock.year - 1970 -leapYearCnt) * 365;
	/*判断当前年是不是闰年*/
	if((clock.year % 4 == 0 && clock.year % 100 != 0) || (clock.year % 400 == 0))
	{
		month = MON2;
	}
	else
	{
		month = MON1;
	}
	
	for(int i = 0; i < clock.month - 1; i++)
	{
		days += month[i];
	}
	
	*pStamp = (days + clock.day-1) * 24 * 3600 * 1000 + clock.hour * 3600 * 1000 + clock.min * 60 * 1000 + clock.sec * 1000 + clock.ms - 8 * 3600 * 1000;
}

int main()
{
	static long long int stamp = 0; 
	timToStamp(&stamp, clock);
	printf("%ld\r\n", stamp);
}

注:所有代码可在菜鸟工具运行


版权声明:本文为m0_37552138原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。