算法 日期处理 两个日期之间的差值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weifenglin1997/article/details/79495195

写程序时会遇到比较两个日期之间的差值,差了多少天,或者其他什么,于是自己写了一个方法,供大家参考,也作为自己的备份吧。大笑

#include <stdio.h>
#include<iostream>
#include <string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
bool runnian(int y){
	return (y%4==0&&y%100!=0)||(y%1000==0);
}
int main(){
    //日期处理YYYYMMDD
    int a,b;
	int m[13][2]={{31,31},{28,29},{31,31},{30,30},{31,31},{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}};
	//处理字符串
	int y1,y2,m1,m2,d1,d2;
	while(scanf("%d%d",&a,&b)!=EOF){
    y1=a/1000;y2=b/1000;
    m1=a/100%100;m2=b/100%100;
    d1=a%100;d2=b%100;
	if(a<b){
		int t=a;
		a=b;
		b=t;
	}
	int sum=1;
	while(y1<y2||m1<m2||d1<d2){
		d1++;
		if(d1>m[m1][runnian(y1)]){
			d1=1;
			m1++;
		}
		if(m1>12){
			y1++;
			m1=1;
		}
		sum++;
	}
	printf("%d\n",sum);
}
	return 0;
}

#include <stdio.h>
#include<iostream>
#include <string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
bool runnian(int y){
	return (y%4==0&&y%100!=0)||(y%1000==0);
}
int main(){
    //日期处理YYYYMMDD
    int a,b;
	int m[13][2]={{31,31},{28,29},{31,31},{30,30},{31,31},{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}};
	//处理字符串
	int y1,y2,m1,m2,d1,d2;
	while(scanf("%d%d",&a,&b)!=EOF){
    y1=a/1000;y2=b/1000;
    m1=a/100%100;m2=b/100%100;
    d1=a%100;d2=b%100;
	if(a<b){
		int t=a;
		a=b;
		b=t;
	}
	int sum=1;
	while(y1<y2||m1<m2||d1<d2){
		d1++;
		if(d1>m[m1][runnian(y1)]){
			d1=1;
			m1++;
		}
		if(m1>12){
			y1++;
			m1=1;
		}
		sum++;
	}
	printf("%d\n",sum);
}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weifenglin1997/article/details/79495195

相关文章