user2720360
user2720360

Reputation: 251

Is mysql datetime not compatible with strtotime()?

I'm passing this function a mysql datetime and it is returning nothing. Is mysql datetime not compatible with strtotime()? I assume that the foreach loop is ending and the return variable is not being called, but why?

function timeAgo($time) {
    $time = time() - strtotime($time); // to get the time since that moment

    $tokens = array (
        1 => 'second',
        60 => 'minute',
        3600 => 'hour',
        86400 => 'day',
        604800 => 'week',
        2592000 => 'month',
        31536000 => 'year'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';
    }
}

Update This is the code that gets it from the database, there are no quotes in the datetime string.

while ($row = mysqli_fetch_assoc($result)) { 
   $commentTime = $row["time"]; 
   $commentComment = $row["comment"]; 
   $commentCommenter = $row["commenter"]; 
} 

And this is the code to echo it: echo '<h3 class="party-time">'.timeAgo($commentTime).'</h3>';

Upvotes: 2

Views: 259

Answers (2)

user2720360
user2720360

Reputation: 251

The problem was a timezone issue. I was manually setting the date in the SQL server I was using which set the datetime to my local time, but the server's timezone was -3 hours, causing issues.

Upvotes: 2

Bart Friederichs
Bart Friederichs

Reputation: 33573

We cannot tell what $time holds exactly, but when you feed an ISO-8601 date to strtotime, it works fine:

php > echo strtotime("2013-08-01 12:00:00");
1375351200

Upvotes: 1

Related Questions