Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Carbon Check If Chosen Date is Greater than Other Date

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.

like image 615
Harry Avatar asked Sep 22 '15 20:09

Harry


People also ask

What is carbon :: now ()?

Carbon::now returns the current date and time and Carbon:today returns the current date.

How do I change the date format in carbon?

Carbon::parse($client->db)->format('d/m/y'); is probably what you're wanting. (parse the yyyy-mm-dd date in the database as a date, and convert it to d/m/y format).


1 Answers

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);

like image 130
Juan Bonnett Avatar answered Oct 22 '22 16:10

Juan Bonnett