How to Convert UTC Time to Local Time in Laravel - TechvBlogs

How to Convert UTC Time to Local Time in Laravel

Master the art of time conversion in Laravel! Learn step-by-step how to seamlessly convert UTC time to local time in your applications. Say goodbye to timezone headaches and elevate your Laravel development game.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

3 months ago

TechvBlogs - Google News

Struggling with time zones in Laravel? This guide cuts through the complexity and shows you how to effortlessly convert UTC to local time using the Carbon library. Follow a clear-cut example to master this essential skill and ensure your users see accurate dates and times, no matter their location. Learn bonus tips on handling Daylight Saving Time and building internationalized applications. Unleash the full potential of Carbon and conquer time zones like a Laravel pro!

Forget time zone headaches! Use Carbon's setTimezone() method in Laravel to magically convert any UTC time to your local setting. Just grab the Carbon library, tell it your timezone ("Asia/Kolkata" in this case), and boom, instantly accurate dates and times for your users! No more complex calculations or cryptic code, just simple Carbon magic.

Now, let's explore some straightforward examples with code:

Example 1:

Explore a simple example with custom date and time:

<?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('2024-01-02 21:20:48')
                        ->setTimezone('Asia/Kolkata')
                        ->toDateTimeString();
                          
        dd($time);
    }
}

Output:

2024-01-03 02:50:48

 Example 2:

Explore a simple example with now date and time:

<?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:

2024-01-02 21:24:10

Thank you! Your input is always appreciated. If you have any more questions or need further assistance, feel free to ask!

Comments (0)

Comment


Note: All Input Fields are required.