Easy Tutorial
❮ Cpp Examples Swapping Cpp Static Members ❯

C Library Function - mktime()

C Standard Library - <time.h>

Description

The C library function time_t mktime(struct tm *timeptr) converts the structure pointed to by timeptr into the number of seconds elapsed since January 1, 1970. It returns -1 if an error occurs.

Declaration

Below is the declaration for the mktime() function.

time_t mktime(struct tm *timeptr)

Parameters

Return Value

The function returns the number of seconds elapsed since January 1, 1970. If an error occurs, it returns -1.

Example

The following example demonstrates the use of the mktime() function.

#include <stdio.h>
#include <time.h>

int main () {
    int ret;
    struct tm info;
    char buffer[80];

    info.tm_year = 2021 - 1900;
    info.tm_mon = 7 - 1;
    info.tm_mday = 4;
    info.tm_hour = 0;
    info.tm_min = 0;
    info.tm_sec = 1;
    info.tm_isdst = -1;

    ret = mktime(&info);
    if( ret == -1 ) {
        printf("Error: unable to make time using mktime\n");
    } else {
        strftime(buffer, sizeof(buffer), "%c", &info );
        printf(buffer);
    }

    return(0);
}

Let's compile and run the above program, which will produce the following result:

Sun Jul  4 00:00:01 2021

Example

/* Determine the day of the week for a given date */
#include <stdio.h>      /* printf, scanf */
#include <time.h>       /* time_t, struct tm, time, mktime */

int main ()
{
    time_t rawtime;
    struct tm * timeinfo;
    int year, month ,day;
    const char * weekday[] = { "Sunday", "Monday","Tuesday", "Wednesday","Thursday", "Friday", "Saturday"};

    /* User inputs the date */
    printf ("Year: "); fflush(stdout); scanf ("%d",&year);
    printf ("Month: "); fflush(stdout); scanf ("%d",&month);
    printf ("Day: "); fflush(stdout); scanf ("%d",&day);

    /* Get current time information and modify it with the input date */
time(&rawtime);
timeinfo = localtime(&rawtime);
timeinfo->tm_year = year - 1900;
timeinfo->tm_mon = month - 1;
timeinfo->tm_mday = day;

/* Call mktime: timeinfo->tm_wday */
mktime(timeinfo);

printf("That day was: %s\n", weekday[timeinfo->tm_wday]);

return 0;
}

Let's compile and run the above program, which will produce the following result:

Year: 2018
Month: 7
Day: 26
That day was: Thursday

C Standard Library - <time.h> ```

❮ Cpp Examples Swapping Cpp Static Members ❯