Você está na página 1de 2

<?

php

$olderDate="19910102";
$newerDate="20140607";

echo$olderDate."is".strtotime($olderDate),"<br>";
echo$newerDate."is".strtotime($newerDate);

CalculateTheDifferenceBetweenTwoDatesInPHP.
ThisisasimpleguideonhowtocalculatethedifferencebetweentwodatesinPHP.Besuretotryout
theexamplesbelowifyourenewtothetopic.

Ourdates.

Letussay,forexample,thatwehavetwodatestringsandthattheyareformattedlikeso:

Asyoucansee,20140607hasamuchbiggertimestamp,simplybecausemoresecondshavepassed
sincethe1stofJanuary,1971andthe7thofJune,2014.

1. 2013030119:12:45
2. 2014030106:37:04

Betweenthenandnow.

Asyoucansee,theresaboutayearinthedifferencebetweenthem.
However,whatifwewanttocalculatetheexactnumberofsecondsthathavepassedbetweendateone
anddatetwo?

Whatifyouneedtofindouthowmanysecondshavepassedsinceagivendate?
<?php

//Ourdatesandtimes.
$then="2011020208:00:00";
$now=time();

//convert$thenintoatimestamp.
$thenTimestamp=strtotime($then);

//Getthedifferenceinseconds.
$difference=$now$thenTimestamp;

echo$difference;

<?php

//Ourdates
$date1="2013030119:12:45";
$date2="2014030106:37:04";

//Convertthemtotimestamps.
$date1Timestamp=strtotime($date1);
$date2Timestamp=strtotime($date2);

//Calculatethedifference.
$difference=$date2Timestamp$date1Timestamp;

echo$difference;

Inthecodeabove:

Ifyourunthecodeabove,youllseethattheansweris:31490659.i.e.31490659secondspassed
between2013030119:12:45and2014030106:37:04.
AbasicdrilldownofwhatIdid:

Ifyoucontinuetorefreshthepage,youllseethatthedifferenceinsecondswillcontinuetogrow.

1. IconvertedbothofourdatestringsintoaunixtimestampbyusingthebuiltinPHP
functionstrtotime.Aunixtimestamprepresentsthenumberofsecondsthathavepassedsince
00:00onthe1stofJanuary,1971.ByconvertingthemintoUnixTime,Iveconvertedthedates
intoaformatthatallowsmetodosomebasiccalculations.
2. Ithensubtractedtheolderdatefromthenewerdate.
Remember:Theolderadateis,thesmalleritscorrespondingtimestampwillbe!Runthefollowing
exampletoseewhatImean:

Iveusedthefunctiontimetoretrievethecurrenttimestamp.i.e.OurcurrentUnixTime.
Ithensubtractedtheoldertimestampfromourcurrenttimestamp.

//Calculatethedifference.
$difference=$now$then;

//Convertsecondsintominutes.
$minutes=floor($difference/60);

echo$minutes;

Minutes&Days
Inmanycases,youllwantthenumberofdaysorminutesthathavepassed.Letsfaceit:Secondsare
kindofuselesstoanenduser.
Tocalculatethenumberofdaysthathavepassed:

<?php

//Our"then"date.
$then="20090204";

//Convertitintoatimestamp.
$then=strtotime($then);

//Getthecurrenttimestamp.
$now=time();

//Calculatethedifference.
$difference=$now$then;

//Convertsecondsintodays.
$days=floor($difference/(60*60*24));

echo$days;

Asyoucansee,itsprettysimple.

OOP
OnceyouvegraspedthefundamentalsofdealingwithdatesandtimestampsinPHP,youshouldlook
intousingtheDateTimeclass,simplybecauseitscleaneranditprovidesyouwithanOOinterface.
Forexample,ifwewanttogetthedifferenceindaysusingtheDateTimeclass,wecandothefollowing:
<?php

$date1=newDateTime("20110706");
$date2=newDateTime();

$diff=$date2>diff($date1)>format("%a");

echo$diff;

Asyoucansee,Iwasabletoconvertsecondsintodaysviasomebasicmath:

Muchbetter.

Thereare60secondsinaminute.
Thereare60minutesinanhour.
Thereare24hoursinaday.

Totransformthedifferenceintoahumanreadableformatthatiscomprisedofyears,months,days,
hoursandminutes:

Ifyoumultiplythefiguresabove,itwillgiveyou86400,whichistotalthenumberofsecondsthatisina
givenday.Dividethedifferenceinsecondsbetweenourtwodatesby86400andyouvegotthenumber
ofdaysthathavepassed.

<?php

$then='2005090109:02:23';
$then=newDateTime($then);

$now=newDateTime();

$sinceThen=$then>diff($now);

//Combined
echo$sinceThen>y.'yearshavepassed.<br>';
echo$sinceThen>m.'monthshavepassed.<br>';
echo$sinceThen>d.'dayshavepassed.<br>';
echo$sinceThen>h.'hourshavepassed.<br>';
echo$sinceThen>i.'minuteshavepassed.<br>';

Youcanthenusethefloorfunctioninordertoroundtheresultdown.i.e.2.9days=2days.
Togetthenumberofminutes,youcansimplydividethedifferenceinsecondsby60,likeso:
<?php

//Our"then"date.
$then="20090204";

//Convertitintoatimestamp.
$then=strtotime($then);

//Getthecurrenttimestamp.
$now=time();

Asyoucansee,theDateTimeclassisprettypowerfulonceyoufigureouttouseit!

Você também pode gostar