简体   繁体   中英

how to compare two dates in if condation in laravel blade?

in my controller i used Carbon to get current timestamp like showing below:

$current_timestamp = Carbon::now()->format('j/n/Y');

the output of the above:

18/8/2022

and i am getting data from external API like showing below (from blade):

$data[0]['DocDate']

the output of the above:

18/8/2022 12:00:00 AM

now i want to remove 12:00:00 AM from it

i tried in blade view to do:

{{Carbon\Carbon::parse($data[29]['DocDate'])->toDateString()}}

but i am getting this error:

Could not parse '18/8/2022 12:00:00 AM': Failed to parse time string (18/8/2022 12:00:00 AM) at position 0 (1): Unexpected character

and i tried:

$data[29]['DocDate']->format('j/n/Y')

and i get this error:

Call to a member function format() on string

how can i overcome this issue?

You can use create from format function to change the format of incoming date as below:

$inDate = $data[0]['DocDate'];

$outDate = Carbon::createFromFormat('d/m/Y h:i:s a', $inDate )->format('d/m/Y');

On the principle of Keep It Simple - Why not just compare them as strings?, the longer one can easily be shortened, then just compare. Accepted this is not a "purest" approach, but the format of a "standard" date is not likely to change.

now i want to remove 12:00:00 AM from it

So you don't actually care about date, you don't need Carbon or parsing according to format, you just need to keep the first word of your string:

{{ explode(' ', $data[0]['DocDate'])[0] }}

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