如何在vc ++ / MFC中计算两个日期之间的确切年,月和日

时间:2013-12-13 05:49:11

标签: visual-c++ mfc

在我的申请中,我必须找出两个日期之间确切的年,月和日。我试着用下面的剪辑。但答案不正确。我用CTime来表示日期。结果在CTimeSpan类中获得。 CTimeSpan具有GetDays等成员函数。我们将从Total Days中找出年,月和日,但答案是不正确的。有什么办法吗?

提前致谢

2 个答案:

答案 0 :(得分:1)

这没有共同的功能。

我的想法是:

  COleDateTime date1(1979,12,31,0,0,0),
               date2(2004,10,01,0,0,0);

  // Get the normal differences
  int iYears = date2.GetYear()-date1.GetYear(),
      iMonths = date2.GetMonth()-date1.GetMonth(),
      iDays = date2.GetDay()-date1.GetDay();

  // Problematic underflow of days. 
  if (iDays<0)
  {
    // One month less
    --iMonths;
    // Advance from the start date until we reach the 1st of next month
    for (iDays=0; (date1+COleDateTimeSpan(iDays,0,0,0)).GetDay()!=1; ++iDays)
      ;

    // Now get the days from the 1st of the second date to the desired date.
    iDays += static_cast<int>((COleDateTime(date2.GetYear(),date2.GetMonth(),1,0,0,0)-date2).GetTotalDays());
  }     

  // underflow of months
  if (iMonths<0)
  {
    --iYears;
    iMonths +=12;
  }

答案 1 :(得分:0)

我在MSDN Docs中找不到任何CTimeSpan::GetTotalDays()功能。

无论如何,GetTotalHours / GetTotalMinutes函数返回完整小时/分钟的数量,并不完全代表TimeSpan值;最好的方法是使用GetTotalSeconds并根据需要进行转换。

相关问题