Mktime function to generate time stamp of any date and time
We can generate number of seconds measured since the Unix Epoch (January 1 1970 00:00:00 GMT) for any given date and time by using mktime function of PHP. Here is the general syntax of mktime() function of PHP.
mktime (hour, minute, second, month, day, year)
This function is useful in doing date calculations like finding difference in two dates. We will learn how to use mktime() function along with date function to generate and check different events.
Let us try to find out the time elapsed on 1st January 2007, 22 hours and 30 minutes & 0 seconds. We will write this code.
$d1=mktime(22,30,0,1,1,2007);
echo $d1;
The output of the above code is 1167670800. Using above output let us use date function find out the date.
As expected the out put of last line is 01/01/2007 22:30:00
Now let us find out the previous day of the above date. The 0th day is considered as last date of the previous month. So check the output of this code. ( only the mktime function is shown here )
By using time() function we can get the seconds elapsed since Unix Epoch (January 1 1970 00:00:00 GMT) and current time.
By using mktime() we get the seconds elapsed since Unix Epoch (January 1 1970 00:00:00 GMT) and given date and time.
When we give current date and time as input to mktime() we get the same output as time() function.
Example :
<?Php
echo "Output of time() : ".time();
echo "<br>";
//echo "output of mktime(): ".mktime(date('H,i,s,m,d,Y',time()));
echo "output of mktime(): ".mktime((int)date('H,i,s,m,d,Y',time()));
?>
Output is here ( Refresh this page to see how the output changes )
Output of time() : 1728673495 output of mktime():1728673495
Here we used date function to generate required format as input for mktime() function.
How many seconds elapsed since starting of this year ?
$year=date('Y');// Current Year
//time stamp of starting of the year
$time1=mktime(0,0,0,01,01,$year);
$elapsed_time=time()-$time1;
echo "Time elapsed in seconds:".$elapsed_time;