C语言计算两个时间的差

输入两个时间,输出两个时间的差值,代码如下:


#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");
}            
                
                
                
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2193410903

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值