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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:44:38  来源:igfitidea点击:

Laravel : How to add days to datetime field?

phplaravel

提问by zwl1619

How to add days to datetime field in Laravel?

如何在 Laravel 的日期时间字段中添加天数?

For example,
there is a updated_atfield in articlestable:

例如,表中
有一个updated_at字段articles

$article = Article::find(1);
$updated_at=$article->updated_at;

I want to add 30 days to updated_atfield.

我想在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_atand created_atfields are automatically cast to an instance of Carbonyou can just do:

由于updated_atcreated_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_atis 2017-09-30 22:43:47then output will be 2017-10-30 22:43:47.000000

假设如果updated_at2017-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));