Javacadabra
Javacadabra

Reputation: 5768

Check if date is before a certain date PHP laravel

I am trying to check if a date is before a certain date. If it is I want to output Valid else output Expired. This is the code I've currently got but all of the entries are being output as Valid which should not be happening.

First I work out the date of this coming Friday which in this case is 2014-10-03, but I want it to be midnight so 2014-10-04 00:00:00.

<?php 
    $lastWed = date('Y-m-d', strtotime('last Wednesday', strtotime('tomorrow')));
    $lastWed = date('Y-m-d H:i:s', strtotime($lastWed.' 11:00:00')); //2014-10-01 11:00:00
    $fri = date('Y-m-d H:i:s', strtotime('+61 hours', strtotime($lastWed)));  //2014-10-04 00:00:00
   //Valid 2014-10-01    //Expired 2014-09-25
?>

Then I use the $fri variable to see if the entry is valid or not. However it is not working. Any thoughts?

@if(date('Y-m-d H:i:s', strtotime($winner->created_at)) <= $fri)
    Valid until <?= $fri ?>
@else
    Expired
@endif

Upvotes: 1

Views: 2483

Answers (2)

Javacadabra
Javacadabra

Reputation: 5768

Never mind guys, I was doing it completely incorrectly. I figured it out for anyone who makes the silly mistake like me. The If was always true because all of the $winner->created_at where in fact before this coming Friday 03rd October 2014.

I added an additional condition to the If to make sure they where between a particular range of dates.

$lastWed = date('Y-m-d', strtotime('last Wednesday', strtotime('tomorrow')));
$lastWed = date('Y-m-d H:i:s', strtotime($lastWed.' 11:00:00')); //2014-10-01 11:00:00
$fri = date('Y-m-d H:i:s', strtotime('+61 hours', strtotime($lastWed))); //2014-10-04 00:00:00
$prevWed = date('Y-m-d H:i:s', strtotime('-1 days', strtotime($lastWed)));
                                ?>
@if($winner->created_at <= $fri && $winner->created_at >= $prevWed)
    Valid until <?= $fri ?>
@else
    Expired
@endif

I worked out the previous Wendsday with this line:

$prevWed = date('Y-m-d H:i:s', strtotime('-1 days', strtotime($lastWed)));

and check to ensure the date is less than or equal to $fri and greater than or equal to $lastWed and problem was solved.

I'd be interested to see how other more experienced programmers might have approached this. I'm sure there are better ways.

Upvotes: 0

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

I would do it this way:

$lastWed = date('Y-m-d', strtotime('last Wednesday', strtotime('tomorrow')));
$lastWed = date('Y-m-d H:i:s', strtotime($lastWed.' 11:00:00')); //2014-10-01 11:00:00
$fri = strtotime('+61 hours', strtotime($lastWed));  

In blade:

@if(strtotime($winner->created_at) <= $fri)
    Valid until {{ $fri }}
@else
    Expired
@endif

Upvotes: 1

Related Questions