显示一年中新的每一天的新信息

Displaying new information for every new day of the year

本文关键字:每一天 新信息 信息 一年 显示      更新时间:2023-10-16

我是C++的新手,目前正试图将当前日期/时间存储在单独的变量中,然后每次日期更改时,都应该显示新的信息。我的代码应该运行如下:

  • 存储日期
  • 检查日期
  • 如果日期与存储的日期不同,则显示信息
  • 存储新日期
  • 重复过程

如何创建商店旧日期和检查新日期功能?

这是我到目前为止的代码,任何帮助都将不胜感激。

#include <ctime>
#include <iostream>
using namespace std;
int main()
{
    time_t t = time(NULL);
    tm* timePtr = localtime(&t);
    cout << "seconds= " << timePtr->tm_sec << endl;
    cout << "minutes = " << timePtr->tm_min << endl;
    cout << "hours = " << timePtr->tm_hour << endl;
    cout << "day of month = " << timePtr->tm_mday << endl;
    cout << "month of year = " << timePtr->tm_mon << endl;
    cout << "year = " << timePtr->tm_year+1900 << endl;
    cout << "weekday = " << timePtr->tm_wday << endl;
    cout << "day of year = " << timePtr->tm_yday << endl;
    cout << "daylight savings = " << timePtr->tm_isdst << endl;
    return 0;
}

这里有一个简单的例子:

#include <fstream>
#include <time.h>
#include <iostream>
int main(int argc, char* argv [])
{
    // first argument is program name, second is timefile
    if (argc == 2)
    {
        // extract time from file (if it exists)
        time_t last_raw;
        std::ifstream ifs;
        ifs.open(argv[1],std::ifstream::in);
        if (ifs.good())
            ifs >> last_raw;
        else
            time(&last_raw); // it does not exist, so create it
        ifs.close();
        // get current time
        time_t now_raw;
        time(&now_raw);
        // compare new to old
        struct tm * now = localtime(&now_raw);
        struct tm * last = localtime(&last_raw);
        if (now->tm_mday != last->tm_day || now->tm_mon != last->tm_mon || now->tm_year != last->tm_year)
        {
            // print whatever here 
        }
        // save new time out to file
        std::ofstream ofs;
        ofs.open (argv[1], std::ofstream::out | std::ofstream::trunc);  // truncate to overwrite old time
        ofs << now_raw;
        ofs.close();
    }
    return 0;
}