Parsing only Time using Carbon

1.7k Views Asked by At

I have a field in my DTO class which accepts start_time and end_time as "2:00 AM"

/**
 * @var string
 */
#[CastWith(TimeCaster::class)]
public string $start_time; // 01:00 AM example

/**
 * @var string
 */
#[CastWith(TimeCaster::class)]
public string $end_time;

Can I parse this format of time using Carbon in my Caster Class

#[\Attribute] class TimeCaster implements Caster
{
    public function cast(mixed $value): mixed
    {
        return Carbon::parse($value)->format();
    }
}
1

There are 1 best solutions below

0
John Lobo On

I think you use Carbon::createFromFormat

Carbon::createFromFormat('H:i A','10:00 PM')->format('Y-m-d H:i:s)

if you want to get only time using timestamp then

Carbon::parse("2021-06-26 22:00:00")->format('g:i A')