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.
echo $d1;
The output of the above code is 1167670800.
Using above output let us use date function find out the date.
echo $d1;
echo "<br>";
echo date("m/d/Y H:i:s",$d1);
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 )
The output of this function is 12/31/2006 22:30:00 .
Generate time stamp by selecting date and time

time() and mktime()

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 :
echo "Output of time() : ".time();
echo "<br>";
echo "output of mktime(): ".mktime(date('H,i,s,m,d,Y',time()));
Output is here ( Refresh this page to see how the output changes )

Output of time() : 1718855029
output of mktime():1718855029
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 
echo "Time elapsed in seconds:".$elapsed_time;
Refresh the page to check change in output
Time elapsed in seconds:14787829

Other ways to get Unix Timestamp

Function Description
strtotime()Text string of data to timestamp
gettimestamp()Getting Timestamp from date object

PHP Date Functions GMT/UTC date/time Date formats for Date()
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer