C++實現兩個日期間差多少天的解決方案

來源:互聯網
上載者:User

計算原理是先求出每個日期距離1年1月1日的天數差值,再進一步做差即可。

複製代碼 代碼如下:#include <stdio.h>
struct MyDate
{
int year;
int month;
int day;
};

int GetAbsDays(MyDate x)
{
int i;
int month_day[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int year = x.year-1; // 因為欲求距離1年1月1日的距離
int days = year * 365 + year/4 - year/100 + year/400; //求得之前閏年的數量並在天數上進行想加
if(x.year%4==0 && x.year%100!=0 || x.year%400==0) month_day[1]++; //當前年為閏年,二月加 1
for(i=0; i<x.month-1; i++)
days += month_day[i];
days += x.day-1; //今天應該是不算如天數計數
return days;
}

int GetDiffDays(MyDate a, MyDate b)
{
return GetAbsDays(b) - GetAbsDays(a);
}

int main(int argc, char* argv[])
{
MyDate a = {1842,5,18};
MyDate b = {2000,3,13};
int n = GetDiffDays(a,b);
printf("%d\n", n);
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.