Skip to main content

Drupal 9: How to get a formatted date string anyway you want with the DrupalDateTime

With the new DrupalDateTime Class it is easier than ever to format a date with php.

One important thing to do before messing with the DrupalDateTime formats and functionality is to set your correct Timezone in admin/config/regional/settings. For my case i switched to Athens - Timezone. Here are some examples based on a timestamp value ($row->created = 1634136039).

   use Drupal\Core\Datetime\DrupalDateTime;

   //Convert Timestamp to Drupal DateTime
   $drupalDateTime = DrupalDateTime::createFromTimestamp($row->created);

   print $drupalDateTime->format('r');
  //Will return "Wed, 13 Oct 2021 17:40:39 +0300"

   print $drupalDateTime->__toString()
  //Will return 2021-10-13 17:40:39 Europe/Athens

  print $drupalDateTime->format('Y-m-d H:i:s')
  //Will return "2021-10-13 17:40:39"

  print $drupalDateTime->format('Y-m-d H:i:s P')
  //Will return "2021-10-13 17:40:39 +03:00"

Now what is important to remember here is that by using the "P" in the format you get the timezone hours difference convertion and this is the only worry free way to always be updated about calculating and displaying the correct date time especially if you are using this in an API call like i do.

Another important thing to notice here is that you should import your language *.po files from here https://localize.drupal.org/translate/languages/ otherwise you won't see any translated strings because they simply do not exist within the database yet!

php date

Latest Articles

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file admin_pixelthi… Sun, 12/01/2024 - 16:49 Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

composer
Controlling ckeditor styling options with hook_editor_js_settings_alter admin_pixelthi… Thu, 05/16/2024 - 10:49 Controlling ckeditor styling options with hook_editor_js_settings_alter

Controlling ckeditor styling options with hook_editor_js_settings_alter

php hook hook_editor_js_settings_alter hook_field_widget_single_[WIDGET_TYPE]_form_alter
Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide admin_pixelthi… Tue, 09/05/2023 - 14:18 Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

composer drupal9 drupal10