insufficient accuracy in time measurement using asTime()

I am trying to update the timestamp column in my Grid view to display the date and time in my local timezone.

[
    'format' => [
       'class' => 'yii\i18n\Formatter',
       'timeZone' => 'Asia/Singapore',
    ],
    'attribute' => 'created_at',
    'label' => 'Date',
    'filter' => false,
    'value'=> function($model, $key, $index, $column){ return Search::getDateTime($model); }, }
    'format' => 'raw',
]

Furthermore, I have added the following method to my search model:

public static function getDateTime($model) {

        $date = Yii::$app->formatter->asDate($model->created_at);
        $time = Yii::$app->formatter->asTime($model->created_at);

        return Html::a($date, null, ['href' => 'javascript:void(0);', 'class' => 'btn btn-link p-0 rounded-0 tooltips', 'data-toggle' => 'tooltip', 'data-placement'=> 'bottom', 'title' => $time]);
    }

In addition to that, make sure your main.php components include the following configuration for the Formatter:

'formatter' => [
            'class' => 'yii\i18n\Formatter',
            'dateFormat' => 'php:j M Y',
            'datetimeFormat' => 'php:d/m/Y h:i a',
            'timeFormat' => 'php:H:i A',
            'defaultTimeZone' => 'Asia/Singapore'
        ],

The timestamps in my database are saved as UTC. For example, 2021-11-22 11:28:16.

If you want to display the correct time based on your timezone (Asia/Singapore), ensure that you follow the steps mentioned above.

Answer №1

Your stored datetimes are in date and time format without any UTC zone reference, making it challenging to automatically convert them to Asia/Singapore datetime. However, since you are aware that the datetimes are in UTC, which is UTC+8 compared to Asia/Singapore, you can simply add 8 hours to your existing datetimes.

To achieve this, I have included a code snippet below:

  • Instantiate a DateTime object using the value from the created_at field.
  • Add 8 hours to the DateTime object.
  • Retrieve the updated created_at value with the added 8 hours.

Here is the code snippet for reference:

public static function getDateTime($model)
{
    $datetime = new DateTime($model->created_at, new DateTimeZone('UTC'));
    $datetime->add(new DateInterval('PT8H'));
    $created_at = $datetime->format('Y-m-d H:i:s');

    $date = Yii::$app->formatter->asDate($created_at);
    $time = Yii::$app->formatter->asTime($created_at);

    return Html::a($date, null, ['href' => 'javascript:void(0);', 'class' => 'btn btn-link p-0 rounded-0 tooltips', 'data-toggle' => 'tooltip', 'data-placement'=> 'bottom', 'title' => $time]);
}

Additionally, an alternative method for converting datetimes from UTC to a specific time zone can be found here: UTC Date/Time String to Timezone

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combine and update JSON files by matching ID's in PHP

I am facing an issue with merging JSON files in PHP. I want to overwrite data when the id's match, but it's not working as expected. Here is my PHP code: foreach($instagram_array['data'] as $key => $image){ $id = $image['id ...

Unable to connect to LAN Network with WampServer 3.2.3

I am having trouble accessing my WampServer machine. Here are my specifications: Windows 10 WampServer 3.2.3.3 64bits Apache 2.4.46 I made changes to the file "D:\Programs\wamp64\bin\apache\apache2.4.46\conf\extra\h ...

The persistent struggle with Symfony2 DB2 doctrine: Creation of the database failed

When attempting to create my database structure in DB2 using Doctrine, I encountered the following response: >php app/console doctrine:database:create Could not create database "monng" for connection named default Notice: Undefined index: dbname Howev ...

The PHP regular expression syntax can be used to capture all occurrences of a specific format

I have a string where I need to extract specific format instances: My new Apple [PT# 789790XYZ; Apple] is great but my colleague has the latest Samsung [PT# GH-5678ujk; Samsung] that's even better. The desired extractions are: [PT# 789790XYZ; App ...

Tips for deleting HTML tags from a database

Whenever I add something to my database, it also includes the html tags. Is there a way to prevent this from happening? public function retrieveDataFromDatabase() { $query = "SELECT * FROM gb ORDER BY id DESC LIMIT 0, 4"; //data output if ...

How can I change the time on Facebook to GMT format?

I have integrated a Facebook application on my website, and when users log in with Facebook, the platform provides timezone information such as 5.5 for (GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi. I am looking for an easy way to convert this informat ...

PHP TypeForm JSON submission

I am new to using JSON, so please forgive me if this is a basic question. A webhook has been set up to send me a JSON Post (Example Below) - I aim to extract the two answers from "text":"250252" & {"label":"CE"} { "event_id": "1", "event_type": " ...

Steps for Displaying a Text with an Image in Laravel 4

Currently, I'm developing an application using Laravel 4. Within my controller, I have implemented a method called show(). This method retrieves the id from the route and creates an array containing specific elements fetched from the database. The arr ...

What is the technique for linking to a different WordPress PHP file using a href?

I have a question regarding working with WordPress. I am using Stacks, a blank theme to convert an HTML template to WordPress. I need to create a hyperlink or button on a landing page that redirects to another PHP file within my website directory (e.g., lo ...

Use a dropdown menu to update the selected value

Issue with displaying drop down values in the second list, despite trying various solutions. When a user selects a country, the corresponding state should be populated from the database into the second drop-down. Any assistance would be greatly appreciated ...

Step-by-Step Guide: Building a PHP-powered AJAX Notification System for Friend Requests

I want to develop a unique notification system using AJAX and incorporate some cool Web 2.0 features. With my PHP expertise, I aim to notify users in real-time when their friend request is accepted by $username. This will be achieved through an interacti ...

Compose an email without the need to access the website

Is there a way to send email reminders to users without having to load the website pages? In the reminder section, users can select a date for their reminder and an email will be automatically sent to them on that date without requiring them to access the ...

PHP will not refresh the page until it has fully loaded

I am interested in writing a crawler script using PHP, but I have encountered an issue with displaying pages in real-time. It seems that PHP does not update the page immediately, sometimes outputting several echos at once and waiting for the page to finish ...

When searching for Arabic letters in PHP MySQL, the results may not always be displayed due to their different shapes

Having an issue with searching for Arabic letters as they have different shapes, like أ إ ا ي ى ه ة Each of these letters have a different unicode value. When entering a letter such as (ا), the search query should retrieve all words containing a ...

Is there a workaround for automatically printing generated PDF files (such as labels and packing slips) from the backend to pre-selected printers directly from a browser?

In the process of creating my web application, I am in need of a solution for automatically printing PDF files (such as labels and packing slips) to pre-selected LAN network printers located in my warehouse from the admin backend. I understand that due to ...

Tips for transferring the id from the url to a php function seamlessly without causing a page refresh

I have a div that includes a button (Book it). When the button is clicked, I want to append the id of the item I clicked on to the current URL. Then, use that id to display a popup box with the details of the clicked item without refreshing the page, as it ...

Guide on embedding PHP/MYSQL array into an independent JavaScript document

I'm looking for guidance on how to insert an array from a PHP MySQL page into a separate JavaScript file. Can someone please help me with indicating where to include the PHP URL and provide the correct format for the PHP array code in order to achieve ...

Using Laravel and AJAX to save multiple selected filters for future use

I've been struggling with this issue for a few weeks now and just can't seem to wrap my head around it. On my webpage, I've implemented four filters: a search filter, a year filter, a launch-site filter, and a country filter. Each of these ...

Using HTML to create interactive table cells

I am looking to add functionality to make a cell in an HTML table clickable. When this action is triggered, I want a pop-up or window to appear with specific information. Below is my current HTML code: <table class="table1"> <thead> <tr ...

Query to retrieve WooCommerce products based on category name using MySQL

I need a solution to update products based on their specific category. Currently, I have successfully retrieved the desired results using the following MySQL query: SELECT * FROM wp_posts WHERE post_type = 'product' At present, there are two pr ...