0

I trying to find a script which will round down a date to the nearest day and tell me how many days different's between them. Want it to return like this:

0 = today 1 = yesterday 2 = 2days ago... you get the idea

This is what ive got so far.

$delta = ((strtotime(date('d/m/y', time())) - strtotime(date('d/m/y', $time))))/86400;

But this returns like this:

0 = for today 30 = yesterday 61 = for the day before....

It driving me mad.....

hakre
  • 193,403
  • 52
  • 435
  • 836
David Allen
  • 1,123
  • 2
  • 10
  • 24

3 Answers3

1

you can switch the month and day in your format for the date function as / is used as separator for the american format.. so it becomes:

$delta = ((strtotime(date('m/d/y', time())) - strtotime(date('m/d/y', $time))))/86400;

that should be all you need but to make it easier to read you can get the current day start just by

$current_day_start = mktime(0, 0, 0);

instead of

((strtotime(date('m/d/y', time()))

and for the other day you could do:

$other_day_start = mktime(0, 0, 0, date('n', $time), date('j', $time), date('Y', $time));

so delta would be

$delta = ($current_day_start - $other_day_start)/86400;
mishu
  • 5,347
  • 1
  • 21
  • 39
  • yes.. the second part was just something I think would be an improvement.. instead of calling the strtotime function (that is one of the slowest as it needs to parse the first param) and the date function (with the second parameter that is not needed for the current time) you can just call the mktime function – mishu Mar 07 '12 at 12:53
0

Try using unix timstamp and doing it this way:

$now = time();
$nearest_day = ....; //a unix timestamp value

//Use "abs" in case nearest day is in the past

$diff =  abs($now - $nearest_day) / (60*60*24);
echo floor($diff);

Works for you?

Ofir Baruch
  • 10,323
  • 2
  • 26
  • 39
0

Try using the format date('Y-m-d', $dateStr) (notice the order of year, month, day), as this is the prefered format for PHP date operations and one of the ISO8601 notations.

Also, there's a problem in the code you posted. No need for this: date('d/m/y', $time), as $time I presume is a string. It actually throws a Notice. See working code below:

$timeStr = '2012-03-06';

$delta = abs((strtotime(date('Y-m-d', time())) - strtotime($timeStr)))/(60*60*24);

echo $delta;

Should output 1, as the current date is 2012-03-07.

binar
  • 1,197
  • 1
  • 11
  • 24