【问题标题】:Check date with C++用 C++ 检查日期
【发布时间】:2013-05-19 11:09:40
【问题描述】:

我想检查当前日期是否是特定的设定日期,如果该日期正确,我希望它运行代码块。否则它将结束脚本。 我在想,会不会是这样的:

int/string? date = ????;

if(date==10/07/13){
    }
else 
    return 0;

我将有一个名为 date 的变量,它将获取当前日期。 我看到的问题是其中有斜线。另外,我想补充一点,我是在英文版 Windows 7 电脑上写这篇文章的,我希望它可以在荷兰文 Windows 7 电脑上打开。这会是个问题吗?

【问题讨论】:

  • 您应该能够使用来自<ctime>std::time 函数,以关于时区的详细信息为模。例如。使用std::localtime 将当前时间戳解析为tm 结构并比较年月日。
  • 听起来是个不错的计划,我得研究一下这个功能,看看我能做什么。非常感谢!

标签: c++ date


【解决方案1】:

这应该让你开始:

#include <ctime>
#include <iostream>

int main()
{
    std::time_t tp = std::time(NULL);   // current time, an integer
                                        // counting seconds since epoch

    std::tm * ts = std::localtime(&tp); // parsed into human conventions


    std::cout << "Year: " << 1900 + ts->tm_year << "\n"
              << "Month: " << ts->tm_mon << "\n"
              << "Day: " << ts->tm_mday << "\n"
        ;
}

除了localtime(使用当前语言环境),您还可以使用gmtime 来获取UTC 时间。

【讨论】:

  • '无法解析标识符 nullptr' 我已经包含了
  • @Darryl:改用NULL。我写了现代 C++;如果您有旧平台,则需要将其调整为 C++98。
  • 'ISO C++ 禁止声明没有类型的 'tp'。我也将其更改为 NULL。
  • @Darryl:正如我所说,如果您没有现代平台,则必须将其移植到 C++98。第一种是std::time_t,第二种是std::tm *
【解决方案2】:
#include <iostream>
#include <string>
#include <ctime>

using namespace std;

string dateString(tm *locTime)
{
return to_string(locTime->tm_year) + "/" + to_string(locTime->tm_mon) + "/" + to_string(locTime->tm_mday)
}

int main( )
{
   time_t now = time(0);
   tm *ltm = localtime(&now);
   if(dateString(ltm)=="YYYY/MM/DD")
   {statements}
}

tm 结构包含整数,如 tm_year、tm_mon、tm_mday。您可以将它们与整数进行比较,或从中构建一个简单的可比较字符串日期格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-15
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 2018-01-18
    • 2018-07-03
    相关资源
    最近更新 更多