创建日期-Laravel中的Carbon [英] Create date - Carbon in Laravel
问题描述
我开始阅读 Carbon
,似乎无法弄清楚如何创建碳日期
.
I'm starting to read about Carbon
and can't seem to figure out how to create a carbon date
.
在文档中说您可以;
Carbon :: createFromDate($ year,$ month,$ day,$ tz);Carbon :: createFromTime($ hour,$ minute,$ second,$ tz);Carbon :: create($ year,$ month,$ day,$ hour,$ minute,$ second,$ tz);
但是,如果我只收到像 2016-01-23
这样的 date
,该怎么办?在创建 carbon
日期之前,我是否必须剥离每个零件并将其喂入 carbon
?或者我会收到 time
,例如 11:53:20
??
But what if I just recieve a date
like 2016-01-23
? Do I have to strip out each part and feed it to carbon
before I can create a carbon
date? or maybe I receive time
like 11:53:20
??
我正在处理动态日期和时间,并编写代码以将时间或日期的各个部分分开感觉不正确.
I'm dealing with dynamic dates and time and writing code to separate parts of time or date doesn't feel right.
任何帮助表示赞赏.
推荐答案
您可以使用以下两种方法之一从该日期字符串创建Carbon实例:
You can use one of two ways of creating a Carbon instance from that date string:
1..创建一个新实例,并将字符串传递给构造函数:
1. Create a new instance and pass the string to the constructor:
// From a datetime string
$datetime = new Carbon('2016-01-23 11:53:20');
// From a date string
$date = new Carbon('2016-01-23');
// From a time string
$time = new Carbon('11:53:20');
2..使用 createFromFormat
方法:
// From a datetime string
$datetime = Carbon::createFromFormat('Y-m-d H:i:s', '2016-01-23 11:53:20');
// From a date string
$date = Carbon::createFromFormat('Y-m-d', '2016-01-23');
// From a time string
$time = Carbon::createFromFormat('H:i:s', '11:53:20');
Carbon类只是扩展了PHP DateTime
类,这意味着您可以使用所有相同的方法,包括相同的构造函数参数或 createFromFormat
方法.
The Carbon class is just extending the PHP DateTime
class, which means that you can use all the same methods including the same constructor parameters or the createFromFormat
method.
这篇关于创建日期-Laravel中的Carbon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!