检查C ++ 11中的失效日期

时间:2017-06-10 16:59:53

标签: c++ c++11 time

我正在使用C ++ 11,我希望根据其发布日期计算项目的到期日期。如果超过30天之前发布的项目,它应该已过期:

#include <ctime>

bool isExpired() {

    std::chrono::system_clock::time_point tend = tstart + std::chrono::hours(30 * 24);
    std::chrono::system_clock::time_point tnow = std::chrono::system_clock::now();

    bool expired = tnow >= tend;
    return expired;
}

但是,我似乎无法简明地输入开始日期。其他一些问题表明有些像

auto ymd = jun/9/2017; // Yields a year_month_day type
std::chrono::system_clock::time_point tstart = sys_days(ymd);

可能在C ++ 11中工作,但Xcode肯定不喜欢它,我不确定我是否跨越了C ++ 14及以上的功能。

在c ++ 11中执行此计算的简洁方法是什么?

2 个答案:

答案 0 :(得分:5)

看起来你正在尝试使用Howard Hinnant's datetime library(这很棒!)。它没有预先安装。从上面的链接获取它。对于您正在使用的部分,您只需要标题"date.h"using namespace date;

使用相同的date.h标头,如果需要,您也可以用days{30}代替hours所使用的表达式。要么有效。

答案 1 :(得分:1)

如果我正确理解了您的问题(run it):

#include <iostream>
#include <chrono>
#include <sstream>
#include <iomanip>

bool is_expired( std::chrono::system_clock::time_point issued_time )
{
  using namespace std;
  using namespace std::chrono;
  typedef duration< int, ratio_multiply < hours::period, ratio<24> >::type > days;
  return duration_cast< days >( system_clock::now() - issued_time ) > days { 30 };
}

auto operator""_issued( const char* s ) // see http://e...content-available-to-author-only...e.com/w/cpp/language/user_literal
{
  std::istringstream iss { s };
  std::tm t {};
  iss >> std::get_time( &t, "%Y%m%d" );
  return std::chrono::system_clock::from_time_t( std::mktime( &t ) );
}

int main()
{
  std::cout << (is_expired( 20170101_issued ) ? "expired" : "valid") << std::endl;
  std::cout << (is_expired( 20170601_issued ) ? "expired" : "valid") << std::endl;
  return 0;
}