How to subYear from date using laravel Carbon

In this article, i will share how to use laravel carbon subYear() and subYears() method. You can use this method in laravel 5, laravel 6, laravel 7 & laravel 8 version.

So, let's see some example using carbon subYear() and subYears() from date.

 

Example: 1

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class ExampleController extends Controller
{
/**
 * Write code on Method
 *
 * @return response()
 */
public function index()
{
$currentDateTime = Carbon::now();
$newDateTime = Carbon::now()->subYear();

print_r($currentDateTime);
print_r($newDateTime);
}
}

Output:

Carbon\Carbon Object

(

[date] => 2022-01-12 16:02:01.522126

[timezone_type] => 3

[timezone] => Asia/Dhaka

)

Carbon\Carbon Object

(

[date] => 2022-01-12 16:02:01.522126

[timezone_type] => 3

[timezone] => Asia/Dhaka

)

 

Example: 2

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class ExampleController extends Controller
{
/**
 * Write code on Method
 *
 * @return response()
 */
public function index()
{
$currentDateTime = Carbon::now();
$newDateTime = Carbon::now()->subYears(5);

print_r($currentDateTime);
print_r($newDateTime);
}
}

 

Output: 

Carbon\Carbon Object

(

[date] => 2022-01-12 16:02:01.522126

[timezone_type] => 3

[timezone] => Asia/Dhaka

)

Carbon\Carbon Object

(

[date] => 2022-01-12 16:02:01.522126

[timezone_type] => 3

[timezone] => Asia/Dhaka

)

Related Post