'PHP DateTime Difference (Hours, Days, Weeks, Months)
I am creating PHP function that will return difference between two dates in a format: 2 Months, 3 Weeks, 6 Days, 3 Hours. I have tried to use PHP DateTime class, but it returns only Months, Days and Hours and I can not find a way to calculate Weeks.
This is my function:
public function DateTimeDifference($FromDate, $ToDate) {
$FromDate = new DateTime($FromDate);
$ToDate = new DateTime($ToDate);
$Interval = $FromDate->diff($ToDate);
$Difference["Hours"] = $Interval->h;
$Difference["Days"] = $Interval->d;
$Difference["Months"] = $Interval->m;
return $Difference;
}
Now, I need $Difference["Weeks"] also included in return data.
EDIT: I know I can divide Days with 7 and get weeks, but this does not result right. For example: 2 Months, 14 Days, 3 Hours - When I divide 14 days with 7 I will get this: 2 Months, 2 Weeks, 14 Days, 3 Hours and now this is not same period.
Solution 1:[1]
public function DateTimeDifference($FromDate, $ToDate) {
$FromDate = new DateTime($FromDate);
$ToDate = new DateTime($ToDate);
$Interval = $FromDate->diff($ToDate);
$Difference["Hours"] = $Interval->h;
$Difference["Weeks"] = floor($Interval->d/7);
$Difference["Days"] = $Interval->d % 7;
$Difference["Months"] = $Interval->m;
return $Difference;
}
Solution 2:[2]
// this will only work from previous dates
// difference between utc date time and custom date time
function FromUtcToCustomDateTimeDifference($ToDate)
{
// Takes Two date time
$UTC_DATE = new DateTime('now', new DateTimeZone('UTC'));
$UTC_DATETIME = $UTC_DATE->format('Y-m-d H:i:s');
// add your own date time 1
$datetime1 = date_create(UTC_DATETIME);
$datetime2 = date_create($ToDate);
$Interval = date_diff($datetime1, $datetime2);
// Count Number Of Days Difference
$Day = $Interval->format('%a');
if($Day > 1)
{
$Month = $Interval->format('%m');
$Year = $Interval->format('%y');
$Week = (int)($Interval->format('%a')/7);
if($Year<1)
{
if($Day <= 7)
{
return $Day > 1 ? $Day.= " days ago" : $Day .= " day ago";
}
else if($Month<1)
{
return $Week > 1 ? $Week.= " weeks ago" : $Week .= " week ago";
}
return $Month > 1 ? $Month.= " months ago" : $Month .= " month ago";
}
else
{
return $Year > 1 ? $Year.= " years ago" : $Year .= " year ago";
}
}
else
{
return "today";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | iXCray |
| Solution 2 | sudo-bhavin |
