如何计算在两个日期之间有多少天在c + + Visual Studio? [英] How to calculate how many days between two dates in c++ visual studio?

查看:246
本文介绍了如何计算在两个日期之间有多少天在c + + Visual Studio?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习C ++,我想尝试使用日期。如何计算两个日期之间的天数?
我尝试使用TimeSpan和DateTime类,但我不能让他们工作..

I have just started learning C++ and I want to try to work with dates now. How can I calculate number of days between two dates? I tried using TimeSpan and DateTime classes, but I can't get them to work..

我发现这在其他线程和一些简单的将是巨大的:

I found this on other thread and something as simple as this would be great:

DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;


推荐答案

StackOverflow中有很多答案。尝试使用搜索。

There are a lot of answers in StackOverflow. Try to use search.

例如,这一个有很好的解决方案:
两个日期之间的天数C ++

For example this one is with good solution: Number of days between two dates C++

#include <iostream>
#include <ctime>

int main()
{
  struct std::tm a = {0,0,0,24,5,104}; /* June 24, 2004 */
  struct std::tm b = {0,0,0,5,6,104}; /* July 5, 2004 */
  std::time_t x = std::mktime(&a);
  std::time_t y = std::mktime(&b);
  if ( x != (std::time_t)(-1) && y != (std::time_t)(-1) )
  {
      double difference = std::difftime(y, x) / (60 * 60 * 24);
      std::cout << std::ctime(&x);
      std::cout << std::ctime(&y);
      std::cout << "difference = " << difference << " days" << std::endl;
  }
  return 0;
}



如果你想以简单的方式使用它使用第三方库如下:
http://howardhinnant.github.io/date_algorithms.html

这篇关于如何计算在两个日期之间有多少天在c + + Visual Studio?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆