Laravel:如何在日期时间字段中添加天数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46504774/
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
Laravel : How to add days to datetime field?
提问by zwl1619
How to add days to datetime field in Laravel?
如何在 Laravel 的日期时间字段中添加天数?
For example,
there is a updated_at
field in articles
table:
例如,表中
有一个updated_at
字段articles
:
$article = Article::find(1);
$updated_at=$article->updated_at;
I want to add 30 days to updated_at
field.
我想在updated_at
字段中添加 30 天。
In Carbon
, it could be done like this:
在 中Carbon
,可以这样做:
$expired_at=Carbon::now()->addDays(30);
But how to do it in above example?
但是在上面的例子中怎么做呢?
回答by DevK
Since updated_at
and created_at
fields are automatically cast to an instance of Carbon
you can just do:
由于updated_at
和created_at
字段会自动转换为Carbon
您可以执行的实例:
$article = Article::find(1);
$article->updated_at->addDays(30);
// $article->save(); If you want to save it
Or if you want it in a separate variable:
或者,如果您希望将其放在单独的变量中:
$article = Article::find(1);
$updated_at = $article->updated_at;
$updated_at->addDays(30); // updated_at now has 30 days added to it
回答by iCoders
you can use Carbon::parse
您可以使用 Carbon::parse
$article = Article::find(1);
$updated_at=Carbon::parse( $article->updated_at)->addDays(30);
Suppose if updated_at
is 2017-09-30 22:43:47
then output will be 2017-10-30 22:43:47.000000
假设如果updated_at
是2017-09-30 22:43:47
那么输出将是2017-10-30 22:43:47.000000
回答by Always Sunny
Have you tried like this with raw php? If you want you can change your datetime format inside first parameter of date()
你试过这样用原始 php 吗?如果您愿意,可以在第一个参数中更改日期时间格式date()
$updated_at=date('Y-m-d H:i:s', strtotime('+30 day', $article->updated_at));