What is mtkime in C?

The mktime function, defined in the time.h header file converts the value of time in it to the corresponding local time zone in the form of a time_t object.

It performs when given an object of type tm as an argument.

Function syntax

Parameters

mktime takes a single, mandatory, argument as a parameter, which is a pointer to a tm structure. Following is the definition of the tm structure:

Elements Represent
tm_sec Seconds passed in a minute
tm_min Minutes passed in an hour
tm_hour Hours passed in a day
tm_mday Months passed in a year
tm_mon Months passed in a year
tm_wday Days passed in a week
tm_yday Days passed in a year
tm_year Years passed since 1900
tm_isdst Daylight saving hours

Return value

The mktime function returns:

  • An mktime object corresponding to the time in the tm object sent as parameter for successful execution.
  • A “-1” if there was an error in execution.

Example

In the following example, we first make and populate a tm object fed as argument to the mktime function. Afterward, we used the ctime function to generate a printable string (of format Www mmm dd hh:mm:ss yyyy) corresponding to the value stored in our the time_t variable populated using the mktime function:

#include<stdio.h>
#include<time.h>
int main()
{
// variable to store the return of the mktime function
time_t my_time;
// variable to give mktime as parameter
struct tm mytm;
// populating the tm object
mytm.tm_year = 2021 - 1900; // 2021
mytm.tm_isdst = 0; // day light saving set to 0
mytm.tm_mon = 1; // January
mytm.tm_mday = 0; // Sunday
// setting the time as 00:00:00
mytm.tm_hour = 0;
mytm.tm_min = 0;
mytm.tm_sec = 0;
my_time = mktime(&mytm);
// converting the time in my_time into a reader
// friendly string of format Www mmm dd hh:mm:ss yyyy
printf(ctime(&my_time));
return 0;
}

The result of the code shows us that the values we put into the tm object were successfully stored in our time_t variable through the mktime function.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved