如何将日期格式YY-MM插入数据库?



我一直在尝试从用户那里获取年份和月份并将它们插入数据库。 我正在使用输入类型月份,以便用户只能发送年份和月份。

<input type="month" name="date_from"/>
<input type="month" name="date_to"/>

这是我的模型

function setDateFromAttribute($value)
{
$this->attributes['date_from'] = CarbonCarbon::createDateFromFormat('Y-m', $value);
}

function setDateToAttribute($value)
{
$this->attributes['date_to'] = CarbonCarbon::createDateToFormat('Y-m', $value);
}

protected $fillable = [
'date_from',
'date_to',
];

数据另存为 0000.00.00 我的数据库中这两个输入的数据类型是

timestamp

我不知道我在这里做错了什么。 请帮忙

我在文档中不认为createDateFromFormat是一种有效的碳方法 https://carbon.nesbot.com/docs/

同样,似乎也没有任何createDateToFormat方法。

Carbon::createFromFormat()返回一个 Carbon 对象,而不是字符串或等效的 MySQL 时间戳,因此,假设您将代码更改为:

$this->attributes['date_from'] = CarbonCarbon::createFromFormat('Y-m', $value)->toDateTimeString();

它应该提供您正在寻找的结果。

引用: 将碳日期转换为 mysql 时间戳。

@Ted Stresen-Reuter

抱歉回复晚了,找不到在模型中工作的解决方案。 尝试了我以前尝试过的方法,但进行了细微的更改。

非常感谢您试图帮助我......我找到了一种方法在控制器中完成此操作,我不推荐,但这是我能够找到的最好的方法,而且我的时间表很紧。

'date_from' => isset($date_from[$key]) ? date('Y-m-d h:i:s', strtotime($date_from[$key])) : '',
'date_to' => isset($date_to[$key]) ? date('Y-m-d h:i:s', strtotime($date_to[$key])) : '',

时间戳类型至少接受完整格式的日期。 正如我知道如何将数据从刀片传递到控制器一样,我能够添加一个日期方法,并在其中添加一个 strttotime 方法将我的 YY-MM 转换为 YY-MM-DD,默认情况下插入的日期将为 01。

最新更新