Change Timezone in Laravel Using Carbon

 

In this blog, We are going to learn how to change the timezone using Carbon in Laravel. This is going to be very simple and I have used this multiple times. 


Laravel Carbon has two methods setTimezone() and tz() which are used to change the timezone. 


Let's start with examples to understand their working,


Using setTimezone()


<?php

  

namespace App\Http\Controllers;

  

use Illuminate\Http\Request;

use Carbon\Carbon;

  

class DemoController extends Controller

{

    /**

     * Write code on Method

     *

     * @return response()

     */

    public function index()

    {

        $time = Carbon::now()->setTimezone("Asia/Kolkata");

          

        dd($time);         

    }

}



Output:


2023-05-25 07:20:42.217710 Asia/Kolkata (+05:30)



Using tz()


<?php

  

namespace App\Http\Controllers;

  

use Illuminate\Http\Request;

use Carbon\Carbon;

  

class DemoController extends Controller

{

    /**

     * Write code on Method

     *

     * @return response()

     */

    public function index()

    {

        $time = Carbon::createFromFormat('Y-m-d H:i:s', '2023-05-25 07:01:01')->tz("Asia/Kolkata");

          

        dd($time);         

    }

}


Output:


2023-05-25 12:31:01.0 Asia/Kolkata (+05:30)


I hope you understood how to change the timezone in Laravel using carbon. If you have any doubt let me know in comments.