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.

php date