1
votes

I have several dates in yyyy-mm-dd format and to manipulate them I am using the Carbon library.

My question is: How can I know if a random date was already in the current year?

For example today is 2018-10-19, if I compare them with some dates, return the following:

$current = '2018-10-19';
$date1 = '2018-10-20'; return false 
$date2 = '2018-11-21'; return false
$date3 = '2018-07-07'; return true

I have tried the following:

$current = Carbon::now();
$date_1 = Carbon::parse('2018-07-21');

if($current > $date_1)
{
    echo 'The date was in the current year';
}

The problem I have is that I do not know how to apply this condition to find a date only in the current year, because if I compare the current date with a date of a previous year, it still returns true. How can I achieve this? Thank you

3
What do you consider the current year? 2018 or the last 365 days?Devon

3 Answers

3
votes

You need to have a closer look at the docs. You can easily compare dates using the equalTo function. An example:

$first = Carbon::create(2012, 9, 5, 23, 26, 11);
$second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');

var_dump($first->equalTo($second));                // bool(false)
var_dump($first->notEqualTo($second));             // bool(true)

That example and more is also listed in the documentation.

2
votes
$current = Carbon::now();
$date_1 = Carbon::parse('2018-07-21');

if($current > $date_1 && $current->year === $date_1->year)
{
    echo 'The date was in the current year';
}

Compare the years with your condition.

1
votes

For a slightly easier to read version, you can use Carbon's between()/isBetween() method in combination with startOfYear():

$date = Carbon::parse('2018-10-19');

if ($date->isBetween(
    Carbon::now()->startOfYear(),
    Carbon::now()
)) {
    echo 'The date was in the current year';
}