C++ - 如何检查今天的日期是否为字符串?

C++ - How to check if today's date is an a string?

本文关键字:日期 是否 字符串 今天 何检查 检查 C++      更新时间:2023-10-16

我有一个我正在开发的C 应用程序,我只需要检查当天的日期是否在char数组中,特别是以" 2015-05-10"的格式。我对C 的新手很陌生,从PHP来看,它很容易做到,但是我正在努力寻找C 中的好方法。当脚本每天在Cron工作中运行时,这需要自动化。因此过程是:

If (today's date is in char array) {
do this } 
else {
do nothing
}

编辑:我显然没有表达问题,对不起!

我的主要问题是:

  1. 我如何以这种格式以一个不错的简单字符串获得当前日期-2015-05-10

  2. 然后我如何检查我存储的char数组(我知道包含其他文本中的日期)是否包含当前日期(当我知道如何将其存储为字符串时)。

如果我正确理解,您的第一个想将当前日期转换为格式yyyy-mm-dd,然后在另一个字符串中搜索字符串。

对于第一个问题,您可以参考如何在C 中获取当前时间和日期?有多个解决方案的地方。对于问题的第二部分,如果您使用的是字符串,则应使用 find (http://www.cplusplus.com/reference/reference/string/string/string/find/)方法,如果您在使用char数组,您可以使用C strstr (http://www.cplusplus.com/reference/reference/cstring/strring/strstr/)方法。这是我尝试的:

       #include <iostream>
       #include <string>
       #include <cstdio>
       #include <ctime>
       #include <cstring>
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[100];
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%Y-%m-%d", &tstruct);
   //char arrays used
    char ch_array[] = "This is the received string 2015-05-10 from server";
    char * pch;
    pch = strstr(ch_array, buf);
    if (pch != nullptr)
        std::cout << "Found";
    //string used
    std::string str("This is the received string 2015-05-10 from server");
    std::size_t found = str.find(buf);
    if (found != std::string::npos)
        std::cout << "date found at: " << found << 'n';