#include<stdio.h>
//计算从1970年-今日,过了多少秒
int main()
{
printf("%d\n", Counting_Seconds(2022, 10, 21, 18, 59, 14));
return 0;
}
//计算秒数,成功返回秒数,超出年限返回1
int mon_table[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };//平年每月的天数
int Counting_Seconds(int year,int mon,int day,int hour,int min,int sec)
{
int secount = 0;
int t = 0;
if (year<1970 || year>2099)return 1;//判断年数是否在合法区间内
for (t = 1970; t < year; t++)
{
if (Is_Leap_Year(t)==1)secount += 31622400;//闰年的秒钟数
else secount += 31536000;//平年的秒钟数
}
mon-= 1;
for (t = 0; t < mon; t++)
{
secount += mon_table[t] * 86400;//把前面月份的秒数相加
if (Is_Leap_Year(year) && t == 1)secount += 86400;//闰年2月多一天
}
secount += (day - 1) * 86400;//把前面天数的秒数相加
secount += hour * 3600;//小时
secount += min * 60;//分钟
secount += sec;//秒
return secount;
}
//判断平年/闰年函数,闰年返回1,平年返回0
int Is_Leap_Year(int year)
{
if (year % 4 == 0 && year % 100 != 0)return 1;
else if (year % 400 == 0)return 1;
else return 0;
}
C语言--计算从1970-今日过了多少秒
于 2022-10-21 18:59:33 首次发布