1

I want to get date with time that is 2 hours ahead. Currently I am trying this: where I add 2 to the hours value

void printTodayFutureTime()
{
        char finalDate[50];
        time_t t;
        struct tm *date;

        memset(finalDate, '\0', 50);

        t = time(NULL);
        date = localtime(&t);
        if(date == NULL)
        {
                printf("Unable to get localtime\n\n");
                return;
        }

        int today = date->tm_mday;
        int month = date->tm_mon + 1;
        int year = date->tm_year + 1900;
        int hour = date->tm_hour;
        int minute = date->tm_min;
        int sec = date->tm_sec;

        snprintf(finalDate, 50, "%d-%d-%dT%d:%d:%d", year, month, today, hour + 2, minute, sec);

        printf("Today's date with future time is: %s\n\n", finalDate);
}

But this will not work if the hour is lets say 22, 23 because it will jump to hour 24 and 25... Can anyone please give me some advice or help.

TheGreatNes
  • 73
  • 1
  • 9
  • 1
    Here is the description of all of the standard time manipulation functions http://port70.net/~nsz/c/c11/n1570.html#7.27.2 – Eugene Sh. May 23 '18 at 18:12
  • if you use the `mktime` system function, it will automatically adjust the values of the `struct tm` value that you pass it, even if they are outside of the normal range. – bruceg May 23 '18 at 18:47

1 Answers1

4

Even if you manage to work around issues with midnight, there's also daylight savings time to take into account, and wrapping months, meaning you have to take leap years into account as well... don't go there.

Instead, it's much easier to just add 2 hours (2 * 60 * 60 seconds) to the time before you convert it to time_t:

    t = time(NULL) + 2 * 60 * 60;
    date = localtime(&t);

This is much more reliable, because a time_t is just the number of seconds since some well-defined epoch.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 1
    Note that it is possible that even though a `time_t` value is usually represented as a number of seconds, this is not guaranteed by C. Adding seconds to a time_t value is not portable, so it is better to use the standard library functions to manipulate the returned value. See this answer for details: https://stackoverflow.com/a/1860996/1212725 – bruceg May 23 '18 at 18:32