ISSUE :
 
Profile photo
Submitted by Sunil Sharma
on May 21st, 2011 at 21:36:28 EST

Format DateTime interval using PHP

I have date1 and date2. I am trying to format difference of two dates like in facebook with "ago" such as "1 year 2 month ago" or "5 hours 3 mins ago."

Any help will be appreciated.


Profile photo
Replied by RaKumar
on May 21st, 2011 at 21:45:23 EST
you can use PHP DateInterval class.
http://www.php.net/manual/en/class.dateinterval.php

Profile photo
Replied by SBajra
on May 21st, 2011 at 21:51:55 EST
Try this out. I am using php DateInterval class. I created a method "FormatDateTimeInterval" with 3 parameters - $dateTime1, $dateTime2 and granularity. Granularity is how many elements of dateTime should be displayed. For example, if granularity=3, 3 elements of DateTime will be diplayed.

<?php
date_default_timezone_set('America/New_York');

$dateTime1 = new DateTime('2009-01-01 12:01:01PM');
$dateTime2 = new DateTime('2011-02-02');

echo FormatDateTimeInterval($dateTime1, $dateTime2, 3);

function FormatDateTimeInterval($dateTime1, $dateTime2, $granularity)
{
$granularityCount = 0;

$interval = $dateTime2->diff($dateTime1);

$formatString = "";

if ($interval->y>0 && $granularityCount<$granularity)
{
$formatString .= "%y year";
if ($interval->y>1)
$formatString .= "s";
$granularityCount++;
}
if ($interval->m>0 && $granularityCount<$granularity)
{
$formatString .= " %m month";
if ($interval->m>1)
$formatString .= "s";
$granularityCount++;
}
if ($interval->d>0 && $granularityCount<$granularity)
{
$formatString .= " %d day";
if ($interval->d>1)
$formatString .= "s";
$granularityCount++;
}
if ($interval->h>0 && $granularityCount<$granularity)
{
$formatString .= " %h hour";
if ($interval->h>1)
$formatString .= "s";
$granularityCount++;
}
if ($interval->i>0 && $granularityCount<$granularity)
{
$formatString .= " %i minute";
if ($interval->i>1)
$formatString .= "s";
$granularityCount++;
}
if ($interval->s>0 && $granularityCount<$granularity)
{
$formatString .= " %s second";
if ($interval->s>1)
$formatString .= "s";
$granularityCount++;
}
return $interval->format($formatString);
}
?>
Accepted Answer
Accepted
 Answer

Profile photo
Replied by Sunil Sharma
on May 21st, 2011 at 21:55:27 EST
Thanks all.

Profile photo
Replied by Albert Isaev
on August 31st, 2012 at 03:22:16 EST
Guys, can you help me with time function I have a table called loan and two columns called loanDate and dueDate, I need to create a function that inserts and returns dueDate.