Sagar Sagar - 1 year ago 71
C Question

Store members of date in different variables

Currently I'm running the following code

int main() {


time_t current = time(NULL);
cout << ctime(&current)<< endl;

and my output looks like this:

Sun Jan 15 00:03:25 2017

Sun Jan 15 00:03:25 2017

As the hours are 00, mins are 03 and secs are 25. I want to store 00 in some integer variable, let's say int hrs, 03 in a variable int min and 25 in a variable int sec. How to do it?

Answer Source

The function you want is localtime.

This function takes the address of a time_t and returns a pointer to a struct tm which contains the date and time broken down into year, month, day, hour, minute, and second.

From the man page:

struct tm *localtime(const time_t *timep);

The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user's specified timezone. The function acts as if it called tzset(3) and sets the external variables tzname with information about the current timezone, timezone with the difference between Coordinated Universal Time (UTC) and local standard time in seconds, and daylight to a nonzero value if daylight savings time rules apply during some part of the year. The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.

The definition of struct tm is as follows:

struct tm {
    int tm_sec;         /* seconds */
    int tm_min;         /* minutes */
    int tm_hour;        /* hours */
    int tm_mday;        /* day of the month */
    int tm_mon;         /* month */
    int tm_year;        /* year */
    int tm_wday;        /* day of the week */
    int tm_yday;        /* day in the year */
    int tm_isdst;       /* daylight saving time */
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download