Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Orgil's avatar
Level 2

Comparing date problem

I'm comparing date which is due date of assignment and today. But when I change the year comparison is not giving true result.

// For example: now 16-12-2016 due_date 01-01-2017
$convert_now = new DateTime('today');
$now = $convert_now->format('d-m-Y');
$now < $check->assignment_due_date ? $date = true : $date = false;

// Result supposed to be "true" but it returns "false"

// now 16-12-2016 due_date 20-12-2016 in this case it's working fine.

PS: I only need to compare date, time not needed. Thanks in advance.

0 likes
4 replies
willvincent's avatar

You'll either want to convert those to timestamps, or better yet just use Carbon, as it makes working with dates painless.

Assuming $check->assignment_due_date is also a DateTime instance:

$date = $now->getTimestamp() < $check->assignment_due_date->getTimestamp() ? true : false;

Or, if these were carbon instances:

date = $now->lt($check->assignment_due_date);

If this doesn't make sense to you, because you don't care about the time, only the date -- remember that time (and date) is calculated based on seconds since Jan 1, 1970.

1 like
jekinney's avatar

In eloquent

whereDate('due_date', Carbon::now()->toDateString());

Add your >, < etc...


$check->due_date->isToday() // true or false
$check->due_date->isFuture(); // true or false (false if today)
$check->due_date->isPast(); // true or false (false if today)

http://carbon.nesbot.com/docs/#api-comparison

if you're checking for the due date being past, then I would use the isPast().

Probably want to output a warning if due today: then maybe if isPast() = false, check if it's today()

1 like
Orgil's avatar
Level 2

@willvincent Thanks for respond.

Since I dont need time, datepicker format is 'd-m-Y' that is the reason why I did not use Carbon.

Anyway I just tried carbon as follows

$now = Carbon::now()->format('d-m-Y');
         $due_date = Carbon::parse($check->assignment_due_date)->format('d-m-Y');
         $date = $now->lt($due_date);

Unfortunately I got following error, It seems date is non Carbon.

Call to a member function lt() on string

Is there any better approach ?

1 like
Orgil's avatar
Orgil
OP
Best Answer
Level 2

@willvincent @jekinney Thanks I've just figured it out

Carbon helped me to get rid of pain of date. Even I don't need time I convert my format to carbon.

$now = Carbon::now();
$due_date = Carbon::parse($check->assignment_due_date);
$now->lt($due_date) ? $date = 1 : $date = 0;

Now it's working.

2 likes

Please or to participate in this conversation.