Conor123
Conor123

Reputation: 3

Displaying new information for every new day of the year

I'm new to C++ and I'm currently attempting to store the current date/time in separate variables, then each time the date changes, new information should be displayed. My code should run as follows:

How do I create the store old date and check new date function?

Here's the code I have so far, any help is greatly appreciated.

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

Upvotes: 0

Views: 330

Answers (1)

Sir Digby Chicken Caesar
Sir Digby Chicken Caesar

Reputation: 3123

Here is a simple example:

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

Upvotes: 1

Related Questions