PHP Carbon Check If Chosen Date is Greater than Other Date
Asked Answered
B

2

20

I've started using PHP Carbon for my application since it seems so much easier than using and manipulating date/time with the DateTime class. What I want to do is check if the chosen date ($chosen_date) is greater than another date ($whitelist_date). I have tried this in the code below:

    $chosen_date = new Carbon($chosen_date);

    $whitelist_date = Carbon::now('Europe/London');
    $whitelist_date->addMinutes(10);

    echo "Chosen date must be after this date: ".$whitelist_date ."</br>";
    echo "Chosen Date: ".$chosen_date ."</br>";

    if ($chosen_date->gt($whitelist_date)) {

        echo "proceed"; 
    } else {
        echo "dont proceed";
    }

The original $chosen_date value comes from POST data. Here is the output I get:

Chosen date must be after this date: 2015-09-22 21:21:57
Chosen Date: 2015-09-22 21:01:00
proceed

Clearly the chosen date is not greater than the whitelist date but still the if statement returns true and echo's "proceed". I have been over the code over and over but I can't see where I have gone wrong.

Buckthorn answered 22/9, 2015 at 20:17 Comment(2)
What does $chosen_date echoes before going into the constructor?Ombre
It echo's the form input eg, 09/22/2015 9:36 PM - in this format.Buckthorn
O
22

It Might be, the time zones are not the same, so try this

$chosen_date = new Carbon($chosen_date, 'Europe/London');

$whitelist_date = Carbon::now('Europe/London');
$whitelist_date->addMinutes(10);

Remember you can always construct the instance and set the timezone for it:

$date = new Carbon();
$date->setTimezone('Europe/London');

$whitelist_date = $date->now();

Any tips on how I can manage data for users with different timezones?

You can create different objects with different Time zones. Try this and play with the results.

$london_date = new Carbon($chosen_date_from_london, 'Europe/London');
$colombia_date = new Carbon($chosen_date_from_colombia, 'Bogota/America');

Let's say you compare them:

$are_different = $london_date->gt($colombia_date);
var_dump($are_different); //FALSE

Nope, they're not different, although they're different times when you stare at the clock and in different parts of the world, they're still in the same Present Moment, the NOW.

There you go, just crate different objects or instances of Carbon(), and set different time zones using $instance->setTimeZone(TimeZone);

Ombre answered 22/9, 2015 at 20:39 Comment(1)
Thanks, I'll get on it!Buckthorn
B
0

Or try using the following one:

if ($chosen_date->gte($whitelist_date))
Brian answered 22/9, 2015 at 20:25 Comment(1)
It does not make a difference.Buckthorn

© 2022 - 2024 — McMap. All rights reserved.