简体   繁体   中英

Laravel compare string date in database with carbon date

I have made a mistake by storing the date as VARCHAR in the database and here it looks like 02/12/2018 and I have created a variable using carbon to get the current date +14 days .

$current_date_plus_14 = Carbon::now() -> addDay(14) -> format('d/m/Y');

Problem is

I am trying to compare this date 02/12/2018 which is in the database and stores as VARCHAR to the date that I have generated using Carbon which is 09/04/2017 .

Eloquent Code

$gquery = Client::where('required_date', '>=', $current_date_plus_14) -> get();

What I get

It doesn't get any results because it compare only the day in the required_date and the day in the carbon date .

While it should return value because the there is more than 1 year difference?

Try this function that converts date as String (May work with varchar) to a real date

private function convertDateString($date)
{
    if (is_string($date)) {
        $date = Carbon::parse($date,new DateTimeZone('YOUR_DATE_TIME_ZONE'));
    }

    return $date;
}

Even if your field is a VARCHAR instead of DATETIME or DATE , you can still mark it as a date in your Eloquent model by adding the attribute name to $dates . You'll also have to change your model's $dateFormat since you have a non- Ymd H:i:s format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM