Drupal - How to get formatted date string from a DateTimeItem object

A date field has two properties, value to store the date in UTC and date, a computed field returning a DrupalDateTime object, on which you can use the methods getTimestamp() or format():

// get unix timestamp
$timestamp = $node->field_date->date->getTimestamp();
// get a formatted date
$date_formatted = $node->field_date->date->format('Y-m-d H:i:s');

For a date range field:

// formatted start date
$start_date_formatted = $node->field_date->start_date->format('Y-m-d H:i:s');
// formatted end date
$end_date_formatted = $node->field_date->end_date->format('Y-m-d H:i:s');

The Accepted answer is good, but for anybody that would like to use the New DrupalDateTime here are few examples.

I. If you have a date and want format it, just pass it to the static method of the class (DrupalDateTime) as follows. You can replace the string with your date variables. Below shows both using the static version and non static version of DrupalDateTime

 $date = DrupalDateTime::createFromFormat('j-M-Y', '20-Jul-2019');
// Using the static method prints out: 20-Jul-2019:11:am

$date = new DrupalDateTime('now');  // grab current dateTime using NON static
$date->format('l, F j, Y - H:i'); // format it 
// prints out nicely formatted version: Tue, Jul 16, 2019 - 11:34:am
// you can remove H:i and what's after it if you don't want hours or am pm

$date = new DrupalDateTime('now');  // grab current dateTime
// Or print $date->format('d-m-Y: H:i A');
// prints out: 16-07-2019: 11:43 AM

More examples:

$date = new DrupalDateTime();
$date->setTimezone(new \DateTimeZone('America/Chicago'));
print $date->format('m/d/Y g:i a');
// The above prints current time for given Timezone
// prints : 07/16/2019 10:59 am

// Another variations of the above except it takes specific date and UTC zone
$date = new DrupalDateTime('2019-07-31 11:30:00', 'UTC');
$date->setTimezone(new \DateTimeZone('America/Chicago'));
print $date->format('m/d/Y g:i a');
// prints 07/31/2019 6:30 am

To use these in your module/code you need to include the following at the top of your file;

 use Drupal\Core\Datetime\DrupalDateTime;

How to test it with Drush Save the above code in a php script let drush run the srcipt after it bootstraps drupal like:

drush -r /path-to-your-drupal-documentRoot -l example.com scr ~/path-to your-script

For multisites make sure you use http://example.com with the drush -l version

Tags:

Datetime

8