contacts_events-8.x-1.x-dev/src/DateRangeFormatter.php
src/DateRangeFormatter.php
<?php
namespace Drupal\contacts_events;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Datetime\DrupalDateTime;
/**
* Provides a date range formatter.
*/
class DateRangeFormatter implements DateRangeFormatterInterface {
/**
* The core date formatter.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* Constructs the date range formatter service.
*
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The core date formatter.
*/
public function __construct(DateFormatterInterface $date_formatter) {
$this->dateFormatter = $date_formatter;
}
/**
* {@inheritdoc}
*/
public function formatDateTimeRange($start_timestamp, $end_timestamp, $type = 'medium', $timezone = NULL, $langcode = NULL) {
$start_date_time = DrupalDateTime::createFromTimestamp($start_timestamp, $timezone);
$end_date_time = DrupalDateTime::createFromTimestamp($end_timestamp, $timezone);
$separator = ' - ';
// Strings containing the ISO-8601 representations of the start and end
// datetime can be used to determine if the date and/or time are the same.
$start_iso_8601 = $start_date_time->format('Y-m-d\TH:i:s');
$end_iso_8601 = $end_date_time->format('Y-m-d\TH:i:s');
if ($start_iso_8601 === $end_iso_8601) {
// The range is a single date and time.
return $this->dateFormatter->format($start_timestamp, $type);
}
elseif (substr($start_iso_8601, 0, 10) == substr($end_iso_8601, 0, 10)) {
// The range is contained within a single day.
$start_text = $this->dateFormatter->format($start_timestamp, $type, '', $timezone, $langcode);
$end_text = $this->dateFormatter->format($end_timestamp, 'custom', 'H:i', $timezone, $langcode);
return $start_text . $separator . $end_text;
}
// Fallback: show the start and end datetimes in full using the default
// pattern. This is the case if the range spans different days,
// or if the other patterns are not specified.
$start_text = $this->dateFormatter->format($start_timestamp, $type, '', $timezone, $langcode);
$end_text = $this->dateFormatter->format($end_timestamp, $type, '', $timezone, $langcode);
return $start_text . $separator . $end_text;
}
}
