Social Icons

Tuesday, April 8, 2014

Calculate difference between two dates in php

Suppose you have two dates as some start date and end date. You have to find the difference between those dates in years, months and days. It can be easily done by converting the date into timestamp value using strtotime function.

Say, you have two dates as follows:

$date1 = "2012-04-24";
$date2 = "2013-05-28";

Convert these dates into timestamp and subtract these.

$difference = abs(strtotime($date2) - strtotime($date1));

Now, you can calculate difference in years, month and days as follows:-

$years = floor($difference / (365*60*60*24));
$months = floor(($difference - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($difference - $years * 365*60*60*24 - $months * 30*60*60*24) / (60*60*24));

Another way to do it using OOP approach as follows:-

$date1 = new DateTime("2012-04-24");
$date2 = new DateTime("2013-05-28");

$interval = $date1->diff($date2);
echo $interval->y ." years ".$interval->m." months ".$interval->d." days";

Thursday, March 20, 2014

Why you shouldn't use mysql_* functions in php?

To use php with mysql database, there are many php functions for it. For example: mysql_connect(), mysql_select_db(), mysql_query(), mysql_real_escape_string() etc. Now you need to move away from it and stop using these functions. 

Very straight forward answer to stop using these functions is that they are outdated. These functions ae likely to be deprecated in higher versions of php. Some important reasons to avoid these can be concluded as below: 
  • They are likely to be deprecated.
  • All Mysql 5.1 functionalities are not supported.
  • They don't support stored procedures.
  • They don't support multiple statements etc.

You can start using mysqli or PDO extensions APIs to do the database sort of things.

Total Pageviews