Monday, April 16, 2012

PHP Date subtraction in hours, minutes, weeks formate

Some times we need to subtract two dates and we need the output in the form of months, weeks, hours and minutes etc. For doing to I wrote a function in php and i would like to share this with you guys...

 <?php  
 function create_time_range($start, $end, $by='30 mins')  
 {  
   $start_time = strtotime($start);  
   $end_time = strtotime($end);  
   $times = array();  
   for ( ;$start_time < $end_time; )  
   {  
     $times[] = $start_time;  
     $start_time = strtotime('+'.$by, $start_time);  
   }  
   $times[] = $start_time;  
   return $times;  
 }  
 // create array of time ranges  
 $times = create_time_range('00:00', '23:00', '30 mins');  
 // more examples  
 // $times = create_time_range('9:30am', '5:30pm', '30 mins');  
 // $times = create_time_range('9:30am', '5:30pm', '1 mins');  
 // $times = create_time_range('9:30am', '5:30pm', '30 secs');  
 // and so on  
 // format the unix timestamps  
 foreach ($times as $key => $time) {  
   $times[$key] = date('G:i', $time);  
 }  
 ?>  



You just need to copy and paste the function create_time_range() in your script and then have to call that function like

create_time_range('9:30am', '5:30pm', '30 secs');

This like will return an array and after printing that array using php function print_r(), you will see the out put.





2 comments:

Please feel free to post your comments. If anyone has a good article or good thing to share, just send me that with your name to asadmehmoodstar@gmail.com. and if anyone want so receive updates regarding my blog, he can subscribe to my weekly newsletter on "Subscribe to our mailing list" section.

Thanks