1

We need to display time along with the date in the admin listing pages. I do know that the tooltip will show the time. But the client needs the time to be displayed on the listing itself. Is there an option in craft CMS to enable this?

1 Answer 1

3

The output format for DateTime attributes is hard-coded in the craft\base\Element class, so there's no configuration you can use to change it. See the source code here for details.

You can, however, use events to overwrite the HTML for any attribute you wish. You're gonna need to create a custom module for this (don't worry, this is pretty straightforward). The event you're looking for is craft\base\Element::EVENT_SET_TABLE_ATTRIBUTE_HTML. You can find example code for event hooks here.

In this case, you're probably looking for the postDate attribute. Using the source code linked above as a starting point, here's a hook to modify the output format for the postDate attribute:

use craft\base\Element;
use craft\events\SetElementTableAttributeHtmlEvent;
use craft\helpers\Html;
use craft\i18n\Locale;
use DateTime;
use yii\base\Event;

Event::on(
    Element::class,
    Element::EVENT_SET_TABLE_ATTRIBUTE_HTML,
    function (SetElementTableAttributeHtmlEvent $e) {
        $attribute = $e->attribute;

        // only modify the `postDate` attribute
        if ($attribute !== 'postDate') return;

        $value = $e->sender->{$attribute};
        if ($value instanceof DateTime) {
            $formatter = Craft::$app->getFormatter();
            $e->html = Html::tag('span', $formatter->asDatetime($value, Locale::LENGTH_LONG), [
                'title' => $formatter->asDatetime($value, Locale::LENGTH_FULL),
            ]);
        }
    }
);

You can find the available formats (LENGTH_* constants) here. Of course, you can also use any custom format you like.

If you want this to apply to ALL attributes that have a DateTime value, leave out the condition that checks if the attribute name is postDate. If you want to only apply this hooks for a particular element type, attach it to the appropriate sub-class instead (for example, craft\elements\Entry instead of craft\base\Element).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.