Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Comparisons show wrong result #2529

Closed
tflori opened this issue Jan 3, 2022 · 1 comment · Fixed by #2530
Closed

Comparisons show wrong result #2529

tflori opened this issue Jan 3, 2022 · 1 comment · Fixed by #2530
Assignees
Labels
Milestone

Comments

@tflori
Copy link
Contributor

tflori commented Jan 3, 2022

Hello,

I encountered an issue with the following code:

Carbon::setToStringFormat('d.m.Y \a\t h:i a');
$dt = Carbon::parse('2022-05-03');
var_dump($dt->gt('2021-05-03'));

Carbon version: 2.55.2

PHP version: PHP 8.0.13

I expected to get:

bool(true)

But I actually get:

bool(false)

Ok, enough of your template. Let me explain. Someone in our company thought it works. And indeed it might work most of the time because noone is touching the to string format and php is smart enough to compare '2022-05-03' > '2021-05-03'. Also the documentation does not say it is save to use strings.

PHP itself also is very broken in this regard as the DateTime cannot be converted to string:

>>> $dt = new DateTime('2022-05-03')
=> DateTime @1651536000 {#189
     date: 2022-05-03 00:00:00.0 UTC (+00:00),
   }
>>> $dt > '2022-06-03'
=> true
>>> $dt > '2021-06-03'
=> true
>>> $dt < '2021-06-03'
=> false
>>> $dt < '2022-06-03'
=> false

The comparisons with strings seem to work more accendtially than anything else. Nevertheless the inline documetnations tells us it is working with strings (see: https://github.com/briannesbitt/Carbon/blob/2.55.2/src/Carbon/Traits/Comparison.php#L147). But that is only true if you don't change the toStringFormat.

My suggestion is to check if the given parameter in the comparison methods is a DateTime object and if not call ::resolveCarbon($date) or directly call ::resolveCarbon($date). Another option would be to throw but that's a breaking change.

Thanks!

@tflori tflori changed the title Comparisions show wrong date Comparisons show wrong result Jan 3, 2022
@kylekatarnls
Copy link
Collaborator

Hello,

I agree. We should use resolveCarbon as we do with most of the methods. Here we want to get any string that parse() is able to handle and don't want to rely to setToStringFormat.

Meanwhile it get changed and released, I suggest to use instead:

$dt = Carbon::parse('2022-05-03');
var_dump($dt->gt(Carbon::parse('2021-05-03')));

Or simply:

var_dump($dt > Carbon::parse('2021-05-04'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
2 participants