如何在 laravel 中将日期增加一个月?

How to increment date by one month in laravel?

我正在将数据存储在数据库中,我想将日期增加一个月。我已经给出了下面的代码。第一行插入成功,但之后数据插入不正确

 $startMonth = $wallet_master->created_at;
      // 31-5-2022
      $endMonth = $wallet_master->created_at->addDays(30);
      //30-6-2022

      for ($i = 0; $i < $wallet_package->wallet_duration; $i++) {

        $data = [   
          'start_date' => $startMonth,
          'end_date' =>   $endMonth,
          ];

        DB::table('wallet_table')->insert($data);
        $startMonth = $endMonth->addDays(1);
        $endMonth =  $startMonth->addDays(30);

您一直拥有相同的 Carbon 实例,因此您需要存储格式化的开始日期和结束日期:

$date = $wallet_master->created_at;
$startMonth = $date->format('d-m-Y');
// 31-5-2022
$endMonth = $date->addDays(30)->format('d-m-Y');
//30-6-2022

for ($i = 0; $i < $wallet_package->wallet_duration; $i++) {

    $data = [   
         'start_date' => $startMonth,
         'end_date' =>   $endMonth,
    ];

    DB::table('wallet_table')->insert($data);
    $startMonth = $date->addDays(1)->format('d-m-Y');
    $endMonth =  $date->addDays(30)->format('d-m-Y');
}
$date = $wallet_master->created_at;

for ($i = 0; $i < $wallet_package->wallet_duration; $i++) {
    $startMonth = $date->copy()->addMonthsNoOverflow($i)->format('d-m-Y');
    $endMonth =  $date->copy()->addMonthsNoOverflow($i + 1)->subDay()->format('d-m-Y');

    DB::table('wallet_table')->insert([   
         'start_date' => $startMonth,
         'end_date' =>   $endMonth,
    ]);
}

注意:如果您使用 CarbonImmutable,则不需要 ->copy()

You can do this with Carbon for adding 1 month:

$startMonth = Carbon::parse($date->created_at)->addMonth(1)->format('d-m-Y');