-1

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!

Tommie
  • 348
  • 1
  • 4
  • 12
  • Use date-diff : http://php.net/manual/fr/function.date-diff.php – Gwenc37 May 27 '14 at 09:05
  • possible duplicate of [Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...](http://stackoverflow.com/a/18602474/67332). Because he stated bellow in one of the comment `Thanks for the answers, but is it also possibile to make this dynamic ? Like this for example : 4 weeks and 3 days ago. 4 months and 3 weeks ago. 4 years and 2 months ago.`. – Glavić May 27 '14 at 15:43

3 Answers3

1

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.

Source : http://www.php.net/manual/en/datetime.diff.php

Akimoto
  • 368
  • 2
  • 11
0

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" : '')
  ;
}
vaibhav
  • 396
  • 2
  • 17
  • `strtotime()` doesn't return miliseconds, but it returns seconds from 1.1.1970.... – Glavić May 27 '14 at 09:38
  • Thanks for the answers, but is it also possibile to make this dynamic ? Like this for example : 4 weeks and 3 days ago. 4 months and 3 weeks ago. 4 years and 2 months ago. – Tommie May 27 '14 at 12:54
0

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()

SEE DEMO


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

SEE DEMO

Mark Miller
  • 7,442
  • 2
  • 16
  • 22