【问题标题】:Get time difference from specific day获取与特定日期的时差
【发布时间】:2016-10-21 09:28:03
【问题描述】:

我试图在chrono 命名空间中找到一些实用程序,以便为我的应用程序提供与C# 程序中相同的功能。我需要做的是计算特定日期之间的时间差,但我找不到任何具体的东西。例如以下是我的 C# 代码:

var startDate = new DateTime(2000, 1, 1);
int diffDays = (DateTime.Today.Date - startDate.Date).Days;

return diffDays.ToString();

C++有没有等价的功能?

【问题讨论】:

    标签: c++ datetime c++11 time chrono


    【解决方案1】:
    // system_clock::from_time_t
    #include <iostream>
    #include <ctime>
    #include <ratio>
    #include <chrono>
    
    int main ()
    {
      using namespace std::chrono;
    
      // create tm with 1/1/2000:
      std::tm timeinfo = std::tm();
      timeinfo.tm_year = 100;   // year: 2000
      timeinfo.tm_mon = 0;      // month: january
      timeinfo.tm_mday = 1;     // day: 1st
      std::time_t tt = std::mktime (&timeinfo);
    
      system_clock::time_point tp = system_clock::from_time_t (tt);
      system_clock::duration d = system_clock::now() - tp;
    
      // convert to number of days:
      typedef duration<int,std::ratio<60*60*24>> days_type;
      days_type ndays = duration_cast<days_type> (d);
    
      // display result:
      std::cout << ndays.count() << " days have passed since 1/1/2000";
      std::cout << std::endl;
    
      return 0;
    }
    

    致谢:http://www.cplusplus.com/reference/chrono/system_clock/from_time_t/

    【讨论】:

    • 我必须用谷歌搜索很多才能找到你的答案:) 谢谢。
    • 对于类似于 diffDays.ToString() 的东西,它可以在 sstream 中使用 std::ostringstream 或在字符串库中使用 std::to_string。
    【解决方案2】:

    这是使用此header-only open source lib 的更简单方法:

    #include "date.h"
    #include <iostream>
    
    int
    main()
    {
        using namespace date;
        using namespace std::chrono;
        auto startDate = 2000_y/jan/1;
        auto diffDays = floor<days>(system_clock::now()) - sys_days{startDate};
        std::cout << diffDays.count() << '\n';
    }
    

    目前输出:

    6138
    

    这里是wandbox link,您可以在其中粘贴上述代码并使用各种版本的 gcc 和 clang 自己尝试一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      • 2013-03-15
      • 2015-04-09
      • 2021-04-23
      • 2018-08-21
      相关资源
      最近更新 更多