首页 > 代码库 > 日期计算

日期计算

#include<stdio.h>#include<iostream>using namespace std;//日期函数int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};struct date{	int year,month,day;};//判闰年inline int leap(int year){	return (year%4==0&&year%100!=0)||year%400==0;}//判合法性inline int legal(date a){	if (a.month<0||a.month>12)		return 0;	if (a.month==2)		return a.day>0&&a.day<=28+leap(a.year);	return a.day>0&&a.day<=days[a.month-1];}//比较日期大小inline int datecmp(date a,date b){   if (a.year!=b.year)	   return a.year-b.year;   if (a.month!=b.month)	   return a.month-b.month;   return a.day-b.day;}//返回指定日期是星期几int weekday(date a){	int tm=a.month>=3?(a.month-2):(a.month+10);	int ty=a.month>=3?a.year:(a.year-1);	return (ty+ty/4-ty/100+ty/400+(int)(2.6*tm-0.2)+a.day)%7;}//日期转天数偏移int date2int(date a){	int ret=a.year*365+(a.year-1)/4-(a.year-1)/100+(a.year-1)/400,i;	days[1]+=leap(a.year);	for (i=0;i<a.month-1;ret+=days[i++]);	days[1]=28;	return ret+a.day;}//天数偏移转日期date int2date(int a){	date ret;	ret.year=a/146097*400;	for (a%=146097;a>=365+leap(ret.year);a-=365+leap(ret.year),ret.year++);	days[1]+=leap(ret.year);	for (ret.month=1;a>=days[ret.month-1];a-=days[ret.month-1],ret.month++);	days[1]=28;	ret.day=a+1;	return ret;}int main(){    date a,b;    a.year=2014,a.month=8,a.day=28;    b.year=2014,b.month=8,b.day=29;    //计算日期之间相差多少天    int t1=date2int(a);//a的天数    int t2=date2int(b);//b的天数    printf("%d\n",t2-t1);    //计算当前日期过了day天的日期    int day=1;    date c=int2date(day+t1);    printf("%d %d %d",c.year,c.month,c.day);    return 0;}

  

日期计算