输入两个时间,输出两个时间的差值,代码如下:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
bool isLeapYear(int year){
if(year%4==0&&year%100!=0){
return true;
}
if(year%400==0){
return true;
}
else{
return false;}
}
void elapsedTime(int y1,int m1, int d1, int y2,int m2, int d2, int &total_day){
int i = 0;
int tmp;
total_day = 0;
const int daysinmonths[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (y1 == y2)
{
if (m1 == m2)
{
total_day = d1 - d2;
total_day = (total_day < 0) ? (-total_day) : total_day;
}
else
{
if (m1 < m2)
{
tmp = y1;
y1 = y2;
y2 = tmp;
tmp = m1;
m1 = m2;
m2 = tmp;
tmp = d1;
d1 = d2;
d2 = tmp;
}
for (i = m2 + 1; i<m1; i++)
{
total_day += daysinmonths[i];
}
total_day += daysinmonths[m2] - d2 + d1;
if (m2 <= 2 && m1 >2)
if (isLeapYear(y2))
total_day++;
}
}
else
{
if (y1 < y2)
{
tmp = y1;
y1 = y2;
y2 = tmp;
tmp = m1;
m1 = m2;
m2 = tmp;
tmp = d1;
d1 = d2;
d2 = tmp;
}
for (i = y2 + 1; i<y1; i++)
{
if (isLeapYear(i))
total_day += 366;
else
total_day += 365;
}
for (i = m2 + 1; i <= 12; i++)
{
total_day += daysinmonths[i];
}
total_day += (daysinmonths[m2] - d2);
if (m2 <= 2)
if (isLeapYear(y2))
total_day++;
for (i = 1; i<m1; i++)
{
total_day += daysinmonths[i];
}
total_day += d1;
if (m1 > 2)
if (isLeapYear(y1))
total_day++;
}
}
int main(){
int m1,d1,y1,m2,d2,y2,total_day;
char ch;
cout<<"Enter start date (no spaces): "<<endl;
cin>>m1>>ch>>d1>>ch>>y1;
cout<<"Enter end date (no spaces): "<<endl;
cin>>m2>>ch>>d2>>ch>>y2;
elapsedTime(y1, m1, d1, y2 , m2, d2, total_day);
cout<<"You have to wait "<< total_day <<" days";
system("pause");
}