Post Details

How to convert UTC to user browser time in laravel blade

How to convert UTC to user browser time in laravel bladeThe code is not working as expected please help. I want to display the time that I grab from the database as UTC into browser time.Latest data atlatest_data_timestampquot time strtotimeutc echo quot quot. datequotYmd Hisquot time.quotquot gt
  • RAMAN TIWARI
    RAMAN TIWARI

    To convert UTC time to the user's browser time in Laravel Blade, you can use JavaScript. Here's how you can achieve it:

    1. Retrieve the UTC time from the database in your Laravel controller.
    2. Pass this UTC time to your Blade view.
    3. Use JavaScript in your Blade view to convert the UTC time to the user's browser time.

    Here's a step-by-step guide:

    1. Retrieve the UTC time in your Laravel controller:
    // ExampleController.php  use App\Models\ExampleModel;  class ExampleController extends Controller {     public function show()     {         // Retrieve the UTC time from the database         $exampleModel = ExampleModel::find($id);         $utcTime = $exampleModel->utc_time;          return view('example', compact('utcTime'));     } } 
    1. Pass the UTC time to your Blade view:
    2. // example.blade.php  @extends('layouts.app')  @section('content')     <div id="utcTime" style="display: none;">{{ $utcTime }}</div>     <!-- Your other HTML content --> @endsection 

    Use JavaScript to convert the UTC time to the user's browser time:

    <!-- example.blade.php -->  <!-- Your other HTML content -->  <script>     // Retrieve the UTC time from the hidden div     var utcTime = document.getElementById('utcTime').innerText;          // Convert UTC time to local browser time     var localTime = new Date(utcTime);          // Format the local time as desired     var formattedLocalTime = localTime.toLocaleString(); // Example format: "4/1/2024, 12:00:00 PM"          // Display the formatted local time wherever you need it in your HTML     document.write("Local Time: " + formattedLocalTime); </script> 

    This JavaScript code will convert the UTC time obtained from the server to the user's local browser time and display it on the page. Adjust the formatting as needed.

Leave A Reply


User name*