PHP: Date Computation [add-minus]

The PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and time.
Tip A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.


Here's some sample tips to calculate DATES in PHP. 
echo date("Y-m-d");
echo date("Y/m/d");
echo date("M d, Y");
echo date("F d, Y");
echo date("D M d, Y");
echo date("l F d, Y");
echo date("l F d, Y, h:i:s");
echo date("l F d, Y, h:i A");

Output
2010-11-30 
2010/11/30 
Nov 30, 2010 
November 30, 2010 
Tue Nov 30, 2010 
Tuesday November 30, 2010 
Tuesday November 30, 2010, 05:58:37 
Tuesday November 30, 2010, 05:58 AM

Calculate Date range of  Start Date and End Date   
$startDate = "11/20/2010"; 
function get_diff_date($target, $today) {

$splitStart = explode("-",$target);    
$splitEnd   = explode("-",$today);    
   
//m-d-y  
$target = mktime(0,0,0,$splitStart[1],$splitStart[2],$splitStart[0]);  
$today  = mktime(0,0,0,$splitEnd[1],$splitEnd[2], $splitEnd[0]);    
    
$difference =($target-$today) ;
$days =(int)($difference/86400) ;
 
    return $days;
}


$today   = date('Y-m-d');
$endDate = "2010-12-29";

$days = get_diff_date($endDate,$today);

print "Our event will occur in $days days";

//OUTPUT : Our event will occur in 28 days 


Definition and Usage

The mktime() function returns the Unix timestamp for a date.
This timestamp contains the number of seconds between the Unix Epoch
(January 1 1970 00:00:00 GMT) and the time specified.

Syntax :

mktime(hour,minute,second,month,day,year,is_dst) 


ADD  MINUS from Current Date

$var = 1; //change value 
$tomorrow  = mktime (0,0,0,date("m") ,date("d") + $var,date("Y")); 
$lastmonth = mktime (0,0,0,date("m")- $var,date("d"), date("Y"));  
$nextyear  = mktime (0,0,0,date("m"), date("d"), date("Y") + $var); 


echo "Tomorrow :  ". date("m/d/Y", $tomorrow);  
echo "Last Month: ". date("m/d/Y", $lastmonth); 
echo "Nexy Year:  ". date("m/d/Y", $nextyear);  

OUTPUT
Tomorrow  : 12/01/2010
Last Month: 10/30/2010
Nexy Year : 11/30/2011

TRICKS on DATE RANGE
-Use range();
$currentYear = date("Y"); 
$years = range($currentYear, 2005); 

  foreach ($years as $value) {
    echo $value ."-";
  }

OUTPUT:  2010 - 2009 - 2008 - 2007 - 2006 - 2005

[ you can also use : range(); ]
$letter = range("a","d");
print_r ($letter);

Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)


Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

1 comments: on "PHP: Date Computation [add-minus]"

Anonymous said...

im useing echo date("l F d, Y, h:i A"); and i need the difference to be -18000 mins how do i do it

:) ) ;) ) ;;) :D ;) :p :( ( :) :( :X =(( :-o :-/ :-* :| 8-} :) ] ~x( :-t b-( :-L x( =))
Post a Comment