如何在日期和时间上使用 Laravel 解析日期时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40375022/
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
How to parse datetime using Laravel on date and time?
提问by MisterPi
I have datetime string: 2016-11-01 15:04:19
我有日期时间字符串: 2016-11-01 15:04:19
How I can get date and time separated?
如何将日期和时间分开?
采纳答案by Christophvh
You can do
你可以做
$model->created_at->format('Y-m-d');
to format a specific date. This solution will only work if your date is a Carbon instance. Or you can use Mutators to format a date by default and make it a Carbon instance if necessary.https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
格式化特定日期。此解决方案仅在您的日期是 Carbon 实例时才有效。或者,您可以使用 Mutators 默认格式化日期,并在必要时将其设为 Carbon 实例。https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
回答by Rwd
Carbon comes with multiple setters
and getters
.
碳带有多个setters
和getters
。
http://carbon.nesbot.com/docs/#api-getters
http://carbon.nesbot.com/docs/#api-getters
If you have a datetime string and you want to use it with a Carbon
instance you can do:
如果您有一个日期时间字符串并且您想将它与一个Carbon
实例一起使用,您可以执行以下操作:
$date = \Carbon\Carbon::parse('2016-11-01 15:04:19');
Then you can do something like:
然后你可以做这样的事情:
$date->format('Y-m-d')
$date->format('H:i:s')
That being said, if you are getting this datetime from an Eloquent
model then you should look at @AlexeyMezenin or @Christophvh answer.
话虽如此,如果您从Eloquent
模型中获取此日期时间,那么您应该查看@AlexeyMezenin 或 @Christophvh 的答案。
Hope this helps!
希望这可以帮助!
回答by Alexey Mezenin
If your date it Carbon object, you can do this:
如果你的日期是 Carbon 对象,你可以这样做:
$date->toTimeString(); // Will output 14:15:16.
$date->toDateString(); // Will output 1975-12-25.
$date->toFormattedDateString(); // Will output Dec 25, 1975.
If you store this date in DB and if it's not Carbon instance, use date mutatorwhich will convert date to istances of Carbon:
如果您将此日期存储在 DB 中,并且它不是 Carbon 实例,请使用日期修改器,它将日期转换为Carbon 的实例:
protected $dates = [
'custom_date',
];
And if you're getting date from some other source, you can create an instance of Carbon and parse()
the date:
如果您从其他来源获取日期,您可以创建一个 Carbon 实例和parse()
日期:
Carbon::parse($custom_date);
After this you can use methods listed above.
在此之后,您可以使用上面列出的方法。