Thursday, 19 December 2013

php strtotime and mktime time functions

We have discussed about php's date and time functions . for refrence please see HERE
Now we are discussing two more functions . strtotime() and mktime() .

strtotime:- 

              This function will convert a string to timestamp format i.e. total number of seconds since 1st jan 1971 .
its usages are like :-

$var1 = strtotime("now");
$var2 = strtotime("10 September 2000");
$var3 = strtotime("+1 day");
$var4 = strtotime("+1 week");
$var5 = strtotime("+1 week 2 days 4 hours 2 seconds");
$var6 = strtotime("next Thursday");
$var7 = strtotime("last Monday");

echo date("Y-m-d H:i:s",$var1) . "<br/>";
echo date("Y-m-d H:i:s",$var2) . "<br/>";
echo date("Y-m-d H:i:s",$var3) . "<br/>";
echo date("Y-m-d H:i:s",$var4) . "<br/>";
echo date("Y-m-d H:i:s",$var5) . "<br/>";
echo date("Y-m-d H:i:s",$var6) . "<br/>";
echo date("Y-m-d H:i:s",$var7) . "<br/>";


explanation of above mentioned code is -
all $var1-7 variable will get timestamp according to string passed to the function  .
'now' will give current timestamp
'+1 day' will give tomorrow's timestamp i.e. +24 hours
and so on ..

also we can find the difference between two dates .
example : suppose we need to find the difference in days between '10 december 2012' and '12 july 1947' .  then we will write that program like this
$time1 = strtotime( "10 december 2012");
$time2 = strtotime( "12 july 1947");
$diff = $time1-$time2 ;
$no_of_days = $diff/86400 ;          // 1 day = 86400 seconds .

mktime :-

             This functions also create timestamp , but it take values as different parameters instead of one complete timed string .following is the syntax for mktime() function
mktime(hour,minutes,seconds,month,date,year,is_dst) ;
all parameters are optional .If we pass each parameter then it will show you the results. Just give a small try to the programs and will understand quickly , what it means . for example -
echo date("M-d-Y",mktime(0,0,0,12,36,2012)) . "<br>";
echo date("M-d-Y",mktime(0,0,0,14,1,2010)) . "<br>";
echo date("M-d-Y",mktime(0,0,0,1,1,1991)) . "<br>";
echo date("M-d-Y",mktime(0,0,0,1,1,99)) . "<br>";


Hope this post will help someone . Please ask me in comments if need any more help .