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

时间:2014-08-25 07:59:10

标签: c++

我是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;
}

1 个答案:

答案 0 :(得分:1)

这是一个简单的例子:

#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;
}