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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:18:34  来源:igfitidea点击:

Create date - Carbon in Laravel

phplaravellaravel-5php-carbon

提问by moh_abk

I'm starting to read about Carbonand 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 datelike 2016-01-23? Do I have to strip out each part and feed it to carbonbefore I can create a carbondate? or maybe I receive timelike 11:53:20??

但如果我只是免费获赠date2016-01-23carbon在创建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 createFromFormatmethod:

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 DateTimeclass, which means that you can use all the same methods including the same constructorparameters or the createFromFormatmethod.

Carbon 类只是扩展了 PHPDateTime类,这意味着您可以使用所有相同的方法,包括相同的构造函数参数或createFromFormat方法。