php 创建日期 - Laravel 中的 Carbon
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34971082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create date - Carbon in Laravel
提问by moh_abk
I'm starting to read about Carbon
and can't seem to figure out how to create a carbon date
.
我开始阅读Carbon
,但似乎无法弄清楚如何创建carbon date
.
In the docs is says you can;
在文档中说你可以;
Carbon::createFromDate($year, $month, $day, $tz); Carbon::createFromTime($hour, $minute, $second, $tz); Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);
Carbon::createFromDate($year, $month, $day, $tz); Carbon::createFromTime($hour, $minute, $second, $tz); Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);
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
??
但如果我只是免费获赠date
样2016-01-23
?carbon
在创建carbon
日期之前,我是否必须剥离每个部分并将其提供给它?或者我收到了time
喜欢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.
我正在处理动态日期和时间,编写代码来分隔时间或日期的各个部分感觉不对。
Any help appreciated.
任何帮助表示赞赏。
回答by Bogdan
You can use one of two ways of creating a Carbon instance from that date string:
您可以使用以下两种方法之一从该日期字符串创建 Carbon 实例:
1.Create a new instance and pass the string to the constructor:
1.创建一个新实例并将字符串传递给构造函数:
// 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.Use the createFromFormat
method:
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');
The Carbon class is just extending the PHP DateTime
class, which means that you can use all the same methods including the same constructorparameters or the createFromFormat
method.
Carbon 类只是扩展了 PHPDateTime
类,这意味着您可以使用所有相同的方法,包括相同的构造函数参数或createFromFormat
方法。