日期问题
日期问题的常规操作
/*给出年份m和一年中的第几天,算出第几天是几月几号,按照yyyy-mm-dd格式打印*/
#include <stdio.h>
int IsYeap(int year){
if(year%400==0||(year%100!=0&&year%4==0)) return 1;
else return 0;
}
int DayOfMonth[13][2]={
0,0,
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 main(){
int m,n;
while(scanf("%d %d",&m,&n)!=EOF){
int month=0;
for(int i=1;i<=12;i++){
if(n>DayOfMonth[i][IsYeap(m)]){
n=n-DayOfMonth[i][IsYeap(m)];
}else{
month=i;
break;
}
}
//c语言的格式输出好处
printf("%d-%02d-%02d\n",m,month,n);
}
}
日期问题相差天数
//太复杂的做法
string s1,s2,tmp;
cin>>s1>>s2;
if(s1>s2){
tmp=s1;
s1=s2;
s2=tmp;
}
string yearS1=s1.substr(0,4),monS1=s1.substr(4,2),dayS1=s1.substr(6,2);
string yearS2=s2.substr(0,4),monS2=s2.substr(4,2),dayS2=s2.substr(6,2);
int year1,mon1,day1,year2,mon2,day2;
year1=atoi(yearS1.c_str());
mon1=atoi(monS1.c_str());
day1=atoi(dayS1.c_str());
year2=atoi(yearS2.c_str());
mon2=atoi(monS2.c_str());
day2=atoi(dayS2.c_str());
cout << year1 <<" "<< mon1 <<" "<<day1<< endl;
//机制简便的处理办法
#include <cstdio>
int month[13][2]={{0,0},{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 main()
{
int time1,y1,m1,d1;
int time2,y2,m2,d2;
while(scanf("%d%d",&time1,&time2)!=EOF)
{
if(time1>time2)
{
int temp=time1;
time1=time2;
time2=temp;
}
y1=time1/10000;m1=time1%10000/100;d1=time1%100;
y2=time2/10000;m2=time2%10000/100;d2=time2%100;
int ans=1;
while(y1<y2||m1<m2||d1<d2)
{
d1++;
if(d1==month[m1][(y1%4==0&&y1%100!=0)||(y1%400==0)]+1)
{
m1++;
d1=1;
}
if(m1==13)
{
y1++;
m1=1;
}
ans++;
}
printf("%d\n",ans);
}
return 0;
}
利用日期差值求星期
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int month[13][2]={{0,0},{31,31},{28,29},{31,31},{30,30},{31,31},
{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}};
char weekname[8][15]={"","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
char monthname[13][15]={"","January","February","March","April","May","June","July","August","September","October","November","December"};
int StringtoNumber(char a[])
{
for(int i=1;i<13;++i)
if(strcmp(a,monthname[i])==0)
return i;
}
void NumbertoString(char a[],int ans,int flag)
{
int b;
if(flag==0)
b=6-ans%7;
else
b=(ans+6)%7;
if(b==0)
b=7;
strcat(a,weekname[b]);
}
int main()
{
char m[20],week[20];
int y1,m1,d1;
while(scanf("%d %s %d",&d1,m,&y1)!=EOF)
{
int y2=2018,m2=1,d2=6,flag=0,ans=0;
m1=StringtoNumber(m);
memset(m,'\0',sizeof(m));
memset(week,'\0',sizeof(week));
if(y1>y2||(y1==y2&&m1>m2)||(y1==y2&&m1==m2&&d1>d2))
{
flag=1;
swap(y1,y2);
swap(m1,m2);
swap(d1,d2);
}
while(y1<y2||m1<m2||d1<d2)
{
d1++;
if(d1==month[m1][(y1%4==0&&y1%100!=0)||(y1%400==0)]+1)
{
m1++;
d1=1;
}
if(m1==13)
{
y1++;
m1=1;
}
ans++;
}
NumbertoString(week,ans,flag);
printf("%s\n",week);
}
return 0;
}