Ben
Ben

Reputation: 5777

How can I check if a given date is newer than 3 days?

I have a date

2016-09-16

How can I check that if that date is less than 3 days old?

I'm being really stupid and the frustration is making me not figure it out

Here's my code

public function isNew()
{
    return strtotime($this->created_at) > time() && strtotime($this->created_at) < strtotime('+3 days',time());
}

Upvotes: 2

Views: 463

Answers (6)

Nour
Nour

Reputation: 1497

Why don't you use Carbon ? You can easily do that and many more in carbon like so :

$dt = Carbon::createFromDate(2011, 8, 1);
echo $dt->subDays(5)->diffForHumans();               // 5 days before

Upvotes: 0

Paul Spiegel
Paul Spiegel

Reputation: 31792

return $this->created_at->diffInDays() < 3;

Without parameter diffInDays() will return the number of complete days between created_at and now.

Upvotes: 0

Brandon M.
Brandon M.

Reputation: 268

This should do it for you.

$date = new DateTime('2015-09-16');
$now = new DateTime();

$interval = $date->diff($now);
$difference = $interval->format('%a');

if($difference < 3) {
    // $date is fewer than 3 days ago
}

In your isNew() method:

public function isNew() {
    $created_at = new DateTime($this->created_at);
    $now = new DateTime();

    $interval = $created_at->diff($now);
    $difference = $interval->format('%a');

    if($difference < 3) {
        return true;
    }

    return false;
}

Upvotes: 1

Robert Wade
Robert Wade

Reputation: 5003

Use diff(). It will return a DateInterval object. Within that object will be a days property (days) that you can access.

// compare two distinct dates:

$datetime1 = new DateTime('2016-09-16');
$datetime2 = new DateTime('2016-09-12');
$interval = $datetime1->diff($datetime2);
$daysOld = $interval->days;
// int(4) 

// or compare today vs your date...

$datetime1 = new DateTime('2016-09-16');
$now = new DateTime();
$interval = $now->diff($datetime1);
$daysOld = $interval->days;
// int(0) 


// then determine if it's at least 3 days old:
$is3daysOld = ($daysOld >= 3 ? true : false);

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

Upvotes: 1

Poiz
Poiz

Reputation: 7617

Using PHP's DateTime and DateInterval Classes would do you much good. Here's how:

<?php

    function isNewerThan3Days($date) {
        $today  = new DateTime();
        $date   = new DateTime($date);

        $diff   = $today->diff($date);
        $diffD  = $diff->days;
        if($diffD>=3){              
            return false;
        }
        return true;
    }

    var_dump(isNewerThan3Days("2016-09-14"));   //<== YIELDS:: boolean true

Upvotes: 1

user1669496
user1669496

Reputation: 33068

Should be easy to use DateTime and DateInterval to handle this.

$date = new DateTime('2016-09-16');

$diff = (new DateTime)->diff($date)->days;

return $diff < 3;

Upvotes: 1

Related Questions