Вы находитесь на странице: 1из 3

Differenceindaysbetweentwodatefieldsofarecord

Differenceindatebetweentwodatecolumnsinatablecanbefoundoutbyconvertingthecolumnsby
usingto_daysfunction.Afterconvertingthatcanbesimplysubtractedtogetthedifference.

Exampleofsuchaapplicationistofindoutthedaysaguesthasstayedinahotel,wehavetotakethe
differenceofarrivaldateanddeparturedate.Boththefieldsaredateandtimefields.Anotherexampleisin
libraryifwearefindingoutthedifferenceindaysbetweendateofissueanddateofreturn.Youcanget
manysuchapplicationswheredifferenceindaysarerequired.Hereisthesqlqueryappliedtoamysqltable
andtheresultisshown.Youcangetthesqldumpofthetableattheendofthistutorial.

Thebasicqueryishere

SELECTTo_days(dt2)TO_DAYS(dt)FROM`dt_tb`

WewillcreateonePHPpagewiththisqueryforeasyunderstandingoftheapplication.

Thesqlqueryismodifiedtodisplayallthecolumnswiththedaydifferenceforeasycomparison.Hereisthe
queryused.

$query="SELECTid,dt,dt2,(To_days(dt2)TO_DAYS(dt))asdifferenceFROM`dt_tb`";

$qt=mysql_query($query);

echomysql_error();

echo"<tableborder='1'cellspacing='1'cellpadding='0'width='400'>

<trvalign='top'>
<td><b>id</b></td><td><b>dt</b></td><td><b>dt2</b></td>

<td><b>difference</b></td></tr>";

while($nt=mysql_fetch_array($qt)){

echo"<trvalign='top'><td>$nt[id]</td><td>$nt[dt]</td><td>$nt[dt2]</td>

<td>$nt[difference]</td></tr>";

echo"</table>";

Theoutputofthisqueryishere
id dt

dt2

2004102600:00:00

20050125 91

2004050523:56:25

20050612 403

2005120813:20:10

20050606 185

Hereisthesqlcodetocreateandfillthetablewithrecords

CREATETABLEdt_tb(

idint(2)NOTNULLauto_increment,

dtdatetimeNOTNULLdefault'0000000000:00:00',

difference

dt2dateNOTNULLdefault'00000000',

PRIMARYKEY(id)

)TYPE=MyISAM;

#Dumpingdatafortable`dt_tb`

INSERTINTOdt_tbVALUES(1,'2004102600:00:00','20050125');

INSERTINTOdt_tbVALUES(2,'2004050523:56:25','20050612');

INSERTINTOdt_tbVALUES(3,'2005120813:20:10','20050606');

Вам также может понравиться