Wednesday, October 23, 2013

Adding and Subtracting Dates (Calculating Time Difference)

Suppose, we want to find how much time is left in Christmas. The current date and time is “20th December 2012, 1:03:47 PM” and Christmas starts at “24 December 2012, 11:59:59 PM”.
Format of your dates should be as “YYYY-MM-DD hh:mm:ss” with 24 hour format.
So,
                Present Time:    2012-12-20 13:03:47
                Future Time:      2012-12-24 23:59:59

Following PHP code gives you the Day, Hours, Minutes and Seconds left.

<?php
     //This is the future time in standart format.
     $fut_time="2012-12-25 23:59:59";    
     //strtotime() function converts the future time into seconds format.
     $fut_time_insecs=strtotime($fut_time);
//The time() function gives the current time in seconds format.
     $pre_time_insecs=time();  
    
//variable left_time_insecs contains the time difference in seconds.
     $left_time_insecs=$fut_time_insecs-$pre_time_insecs;

     //This gives the seconds.
     $seconds=$left_time_insecs%60;
     //Total minutes left
     $left_time_inmins=floor($left_time_insecs/60);
    
     //This gives the minutes.
     $minutes=$left_time_inmins%60; 
     //Total hours left
     $left_time_inhrs=floor($left_time_inmins/60);
    
     //This gives the seconds.
     $hours=$left_time_inhrs%60;    
     //Total minutes left
     $left_time_indays=floor($left_time_inhrs/60);
    
     //Total days left
     $days=$left_time_indays;
    
     //Displays Days, Hours, Minutes and Seconds left
     echo "Christmas: ".$days." Days ".$hours." Hours ".$minutes." Minutes ".$seconds." Seconds Left";
?>

OUTPUT:

Christmas: 2 Days 10 Hours 56 Minutes 12 Seconds Left


Visit http://www.webolute.com and access free application for your business or personal use.

No comments:

Post a Comment