使程序检查当前日期是否=预期日期

Make a program check if current date = intended date

本文关键字:日期 是否 程序 检查 当前日期      更新时间:2023-10-16

有没有办法让 c++ 等到预定的日期,什么时候应该继续处理其余的代码?

我不希望它使用等待或睡眠之类的东西等待,我实际上希望它只是使用 if 语句进行检查。极其糟糕的伪代码示例:

if current_date == intended_date
cout << "Happy Birthday";
end 

我希望程序只有在满足生日条件的情况下才说生日快乐。我知道您可以使用 std::chrono::system_clock::now(( 获取当前日期。但是,我不知道如何格式化intended_date以便它可以根据当前日期进行检查。

我认为标准模块chrono和iomanip为您提供了所需的内容:

#include <chrono>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <list>
int main()
{
auto currentTime = std::chrono::system_clock::to_time_t(
std::chrono::system_clock::now()
);
std::stringstream timeStream;
timeStream << std::put_time(std::localtime(&currentTime), "%m-%d");
const std::list<std::string> birthdays = {"12-08", "10-03"};
for (auto& date : birthdays)
{
if(timeStream.str() == date)
{
std::cout << "Happy birthday!!n";
}
else
{
std::cout << "Try another day!!n";
}
}
return 0;
}