mktime() function in C++ STL

The mktime() is an inbuilt C++ function which converts the local calendar time to the time since epoch and returns the value as an object of type time_t.

Syntax :

time_t  mktime( struct tm  *time_ptr )

Parameters: The function accepts a mandatory parameter pointer time_ptr that points to a tm object structure which contains a calendar time whihc is to be converted.

Return Value: The function returns two type of values as described below:

  • It returns the time since epoch as an object of type time_t if the parameter passed is a success.
  • It returns -1 on failure.

Below program illustrates the mktime() function:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to demonstrate the
// mktime() function
  
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    time_t tim;
    tm* time_ptr;
    char weekday[7][20] = { "Sunday",
                            "Monday",
                            "Tuesday",
                            "Wednesday",
                            "Thursday",
                            "Friday",
                            "Saturday" };
  
    // Date
    int year = 2018;
    int month = 6;
    int day = 18;
  
    time(&tim);
    time_ptr = localtime(&tim);
  
    // tm_year is time since 1900
    time_ptr->tm_year = year - 1900;
  
    // Months calculated since January
    time_ptr->tm_mon = month - 1;
  
    // Day calculated in the month
    time_ptr->tm_mday = day;
  
    // time_ptr pointer to be pass
    mktime(time_ptr);
  
    cout << "Tha Day on 18th June 2018 was "
         << weekday[time_ptr->tm_wday];
  
    return 0;
}

chevron_right


Output:

Tha Day on 18th June 2018 was Monday


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.