计算多少天后的日期

有的时候我会想,再过个100天是几月几日呢?也许你可以翻翻日历,但是如果是1000天、10000天以后呢?为什么我们不写个小程序来专门处理这个问题呢?似乎也不是很复杂……
于是这篇博客应运而生,其实计算的逻辑很简单,就是使用计算机模拟日期计数,比较有特色的地方在于switch-case的“非常规”运用——

/ *
* 文件名:nextdate.c
* 作者:于子豪
* 描述:计算多少天后的日期
* 日期:2019-7-30
  */
#include <stdio.h>
typedef struct date
{
	int year;
	int month;
	int day;
}Date;

//是否是闰年判断
int isbissextile(int year)
{
	if(((year%100!=0)&&(year%4==0))||year%400==0)
	  return 1;
        else return -1;
}

Date todate(Date today, int days)
{
	int day=today.day+days;
	while(1) 
	{
		switch(today.month)
		{
			case 1:
			  if(day>31) {day-=31;today.month++;}
			  else {today.day=day;return today;}
			case 2:
			  if(day*isbissextile(today.year)>29) {day-=29;today.month++;}
			  else if(day*isbissextile(today.year)<-28) {day-=28;today.month++;}
			  else {today.day=day;return today;}
			case 3:
			  if(day>31) {day-=31;today.month++;}
			  else {today.day=day;return today;}
			case 4:
			  if(day>30) {day-=30;today.month++;}
			  else {today.day=day;return today;}
			case 5:
			  if(day>31) {day-=31;today.month++;}
			  else {today.day=day;return today;}
			case 6:
			  if(day>30) {day-=30;today.month++;}
			  else {today.day=day;return today;}
			case 7:
			  if(day>31) {day-=31;today.month++;}
			  else {today.day=day;return today;}
			case 8:
			  if(day>31) {day-=31;today.month++;}
			  else {today.day=day;return today;}
			case 9:
			  if(day>30) {day-=30;today.month++;}
			  else {today.day=day;return today;}
			case 10:
			  if(day>31) {day-=31;today.month++;}
			  else {today.day=day;return today;}
			case 11:
			  if(day>30) {day-=30;today.month++;}
			  else {today.day=day;return today;}
			case 12:
			  if(day>31) {day-=31;today.month=1;today.year++;}
			  else {today.day=day;return today;}
			default:break;
		}
	}
	
}

//测试程序
int main(int argc, char *argv[])
{
	Date today={1999,1,11};
        int days=117+365;
        printf("今天是%d.%d.%d:经过%d天后是:",today.year,today.month,today.day,days);
	Date nextday=todate(today,days);
	printf("%d.%d.%d\n",nextday.year,nextday.month,nextday.day);
	return 0;
}

最后,附上一个C-Free5的压缩包:
https://download.csdn.net/download/qq_45467083/11453165

上一篇:test


下一篇:2021-06-04