仅使用 Carbon 解析时间

问题描述

我的 DTO 类中有一个字段,它接受 start_time 和 end_time 为“凌晨 2:00”

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

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

我可以在我的 Caster 类中使用 Carbon 解析这种时间格式吗

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

解决方法

我认为您使用了 Carbon::createFromFormat

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

如果您只想使用时间戳获取时间,则

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