Convert UTC Time to Local Time in laravel

Posted by

I will demonstrate how to use Laravel to convert UTC to local time in this section. We’ll assist you by providing a sample of how to convert UTC to local time using Laravel Carbon. I gave a brief explanation on how to use Laravel to convert UTC time to local time. I will demonstrate how to use Laravel to convert UTC to local time. So let’s develop an example of converting UTC to local time in Ruby using a few simple steps.

The Carbon setTimezone() method will be utilized in Laravel to convert UTC time to local time. The setTimezone() function requires you to provide in your local timezone as an input. We shall convert the UTC time in this example to my local time, “Asia/Kolkata”.

Example of controller code:

<?php
     
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Carbon\Carbon;
    
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $time = Carbon::parse('2023-10-18 20:25:48')
                        ->setTimezone('Asia/Kolkata')
                        ->toDateTimeString();
                          
        dd($time);
    }
}

OutPut:

2023-10-19 01:55:48

Example 2:

<?php
     
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Carbon\Carbon;
    
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $time = Carbon::now()
                    ->setTimezone('Asia/Kolkata')
                    ->toDateTimeString();
  
        dd($time);
    }
}

OutPut:

2023-10-19 09:23:56

Leave a Reply

Your email address will not be published. Required fields are marked *

0
Would love your thoughts, please comment.x
()
x