i have a date and want to count the time between now and the date. ALso i want to return the time between the 2 dates in this example format:
4 weeks and 3 days ago.
Is this possible in PHP?
I hope you guys can help me!
i have a date and want to count the time between now and the date. ALso i want to return the time between the 2 dates in this example format:
4 weeks and 3 days ago.
Is this possible in PHP?
I hope you guys can help me!
Here an example :
<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>
Will echo +2 days.
Determine the time(in seconds) between two dates :
strtotime($human_readable_date);
now subtract the time between two dates
$seconds = strtotime1($date1) - strtotime1($date2);
now get the actual time from these seconds you can get this time in your own format, just change the formatting type in this function
function formatSeconds( $seconds )
{
$hours = 0;
$milliseconds = str_replace( "0.", '', $seconds - floor( $seconds ) );
if ( $seconds > 3600 )
{
$hours = floor( $seconds / 3600 );
}
$seconds = $seconds % 3600;
return str_pad( $hours, 2, '0', STR_PAD_LEFT )
. gmdate( ':i:s', $seconds )
. ($milliseconds ? ".$milliseconds" : '')
;
}
Use date_diff() and a little math:
$now = new DateTime('now');
$date = new DateTime('2014-05-01');
// Total difference in days
$total_days = date_diff($now, $date)->format('%a');
// Get weeks
$weeks = floor($total_days / 7);
// Get days
$days = $total_days % 7;
echo $weeks . ' weeks and ' . $days . ' days ago';
Output:
3 weeks and 5 days ago
Notes:
(1) date_diff()
is valid in PHP v 5.3 and above.
(2) You may need to specifiy timezone using DateTimeZone()
OR, for PHP version < 5.3, use strtotime():
$now = time();
$date = strtotime('2014-05-01');
$total_days = floor(($now - $date)/60/60/24);
$weeks = floor($total_days / 7);
$days = $total_days % 7;
echo $weeks . ' weeks and ' . $days . ' days ago';
Output:
3 weeks and 5 days ago