You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中设置日期为上月并让新增记录用上月时间戳?

Laravel中设置上个月日期及回溯时间戳实现方法

一、将日期设置为上个月

Laravel依赖Carbon处理日期时间,以下是几种常见的设置方式:

  • 获取上个月的当前时刻:使用subMonth()方法直接回溯一个月
    $lastMonthNow = \Carbon\Carbon::now()->subMonth();
    
  • 获取上个月的第一天:先定位到当前月第一天,再回溯一个月
    $lastMonthFirstDay = \Carbon\Carbon::now()->startOfMonth()->subMonth();
    
  • 获取上个月的最后一天:先定位到当前月最后一天,再回溯一个月
    $lastMonthLastDay = \Carbon\Carbon::now()->endOfMonth()->subMonth();
    
  • 将指定日期转为上个月对应日期:对已有的Carbon实例调用subMonth()
    $date = \Carbon\Carbon::parse('2024-06-20');
    $lastMonthDate = $date->subMonth(); // 结果为2024-05-20
    

二、实现回溯时间功能(新增记录时间戳统一为上个月)

如果需要让所有新增记录的时间戳(如created_at/updated_at)默认使用上个月的时间,可通过以下方式实现:

1. 全局生效(所有模型)

在App\Providers\AppServiceProvider的boot方法中添加全局模型事件监听:

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

public function boot()
{
    // 新增记录时设置时间为上个月
    Model::creating(function ($model) {
        $model->created_at = Carbon::now()->subMonth();
        $model->updated_at = Carbon::now()->subMonth();
    });

    // 若需要更新记录时也沿用上个月时间,取消下面注释
    // Model::updating(function ($model) {
    //     $model->updated_at = Carbon::now()->subMonth();
    // });
}

2. 单个模型生效

仅针对特定模型修改时间戳,在对应模型的boot方法中定义事件:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Order extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($order) {
            $order->created_at = Carbon::now()->subMonth();
            $order->updated_at = Carbon::now()->subMonth();
        });
    }
}

3. 自定义时间字段处理

如果模型有自定义时间字段(如published_at),同样在创建事件中赋值:

static::creating(function ($model) {
    $model->published_at = Carbon::now()->subMonth();
});

4. 临时单次操作

仅需某一次新增记录使用上个月时间时,直接手动赋值字段:

use App\Models\Post;
use Carbon\Carbon;

Post::create([
    'title' => '回溯时间测试',
    'content' => '测试内容',
    'created_at' => Carbon::now()->subMonth(),
    'updated_at' => Carbon::now()->subMonth()
]);

内容的提问来源于stack exchange,提问作者Don40

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 17:58:07