Hello, web developers! In this article, we'll see how to convert UTC time to local time in laravel 10. UTC literally stands for Universal Time Coordinated though it is typically referred to as Coordinated Universal Time and is the standard time common to every place in the world.
Here, we'll use the carbon parse function to convert the local timezone.
Laravel 10 Convert UTC to Local Time
In Laravel, configuring the application's default timezone is the initial step. Open the config/app.php
file and locate the timezone
key. Set it to your preferred time zone. For instance, if you want to set it to 'UTC', you would write:
'timezone' => 'UTC',
To streamline the process of converting UTC to local time throughout your application, creating a helper function is beneficial. Open the app/Helpers
directory or create it if it doesn't exist. Then, create a new file, for example, TimeHelper.php
, and define your helper function:
<?php
// app/Helpers/TimeHelper.php
use Carbon\Carbon;
function convertToLocale($time)
{
return Carbon::parse($time)->timezone(config('app.timezone'));
}
Utilize the convertToLocale
helper function in your controllers, views, or any other relevant components where UTC needs to be converted to local time.
use App\Helpers\TimeHelper;
public function show($id)
{
$post = Post::find($id);
$localizedCreatedAt = TimeHelper::convertToLocale($post->created_at);
return view('post.show', compact('post', 'localizedCreatedAt'));
}
Now that you've converted the UTC to local time, you can easily display it in your views. For example:
<p>Created at: {{ $localizedCreatedAt->format('Y-m-d H:i:s') }}</p>
This will output the localized creation time of the post.
Example:
<?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-07-021 12:21:22
You might also like:
- Read Also: Laravel 10 Create Form Request Validation
- Read Also: How to Get Current Date and Time in React Native
- Read Also: How to Get Current Date and Time in Python
- Read Also: How to Import Excel File into Database using Python