[英]How to parse datetime using Laravel on date and time?
I have datetime string: 2016-11-01 15:04:19
我有日期时间字符串:
2016-11-01 15:04:19
How I can get date and time separated?如何将日期和时间分开?
Carbon comes with multiple setters
and getters
. Carbon 带有多个
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!希望这有帮助!
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.
此解决方案仅在您的日期是 Carbon 实例时才有效。 Or you can use Mutators to format a date by default and make it a Carbon instance if necessary.
或者,您可以使用 Mutators 默认格式化日期,并在必要时将其设为 Carbon 实例。https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
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 mutator which will convert date to istances of Carbon:如果您将此日期存储在 DB 中,并且它不是 Carbon 实例,请使用date mutator将日期转换为 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.在此之后,您可以使用上面列出的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.