Search code examples
phpjoomla

Formating a date from database query


I have a query on a Joomla database which works ok except that the date from the "modified" field is not in the desired format. It's presented as 2021-04-30 01:09:56 and I would like it as April 30, 2021. Can someone enlighten me on how to format the $row['modified'] to achieve the desired result.

my query code is:

<?php
defined('_JEXEC') or die('Restricted Access');
use Joomla\CMS\Factory;
$db = Factory::getDbo();
$me = Factory::getUser();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('id', 'title' ,'modified')))
->from($db->quoteName('#__content'))
->where($db->quoteName('id') . ' = 114');
$db->setQuery($query);
// echo $db->replacePrefix((string) $query);
$results = $db->loadAssocList();
foreach ($results as $row) {
 echo "<p>" . $row['id'] . ", " . $row['title']. ", " . $row['modified']. "<br></p>";   
} 

Solution

  • <?php
    defined('_JEXEC') or die('Restricted Access');
    use Joomla\CMS\Factory;
    $db = Factory::getDbo();
    $me = Factory::getUser();
    $query = $db->getQuery(true);
    $query->select($db->quoteName(array('id', 'title' ,'modified')))
    ->from($db->quoteName('#__content'))
    ->where($db->quoteName('id') . ' = 114');
    $db->setQuery($query);
    // echo $db->replacePrefix((string) $query);
    $results = $db->loadAssocList();
    foreach ($results as $row) {
        $newDate = date('F j,Y', strtotime($row['modified']));
        echo "<p>" . $row['id'] . ", " . $row['title']. ", " .$newDate. "<br></p>";   
    } 
    

    This is the solution for your problem. Check this for more informations about this

    https://www.php.net/manual/de/function.strtotime.php

    https://www.php.net/manual/de/function.date.php