Formatting Dates programmatically with the Drupal date formatter service
Example for a single datetime field
Example for a daterange field
Issue:
You need to format datetime objects before printing them.
Solution:
The Drupal date formatter service will be your friend. If you have enabled the datetime and/or datetime_range Core modules, you can set it to a defined date format (/admin/config/regional/date-time) or use a custom one. Details about the parameters you can use can be found on php.net.
We recommend always choosing the Drupal solution instead of a custom solution whenever possible.