3 namespace Drupal\views\Plugin\views\sort;
5 use Drupal\Core\Form\FormStateInterface;
8 * Basic sort handler for dates.
10 * This handler enables granularity, which is the ability to make dates
11 * equivalent based upon nearness.
15 class Date extends SortPluginBase {
17 protected function defineOptions() {
18 $options = parent::defineOptions();
20 $options['granularity'] = ['default' => 'second'];
25 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
26 parent::buildOptionsForm($form, $form_state);
28 $form['granularity'] = [
30 '#title' => $this->t('Granularity'),
32 'second' => $this->t('Second'),
33 'minute' => $this->t('Minute'),
34 'hour' => $this->t('Hour'),
35 'day' => $this->t('Day'),
36 'month' => $this->t('Month'),
37 'year' => $this->t('Year'),
39 '#description' => $this->t('The granularity is the smallest unit to use when determining whether two dates are the same; for example, if the granularity is "Year" then all dates in 1999, regardless of when they fall in 1999, will be considered the same date.'),
40 '#default_value' => $this->options['granularity'],
45 * Called to add the sort to a query.
47 public function query() {
48 $this->ensureMyTable();
49 switch ($this->options['granularity']) {
52 $this->query->addOrderBy($this->tableAlias, $this->realField, $this->options['order']);
55 $formula = $this->getDateFormat('YmdHi');
58 $formula = $this->getDateFormat('YmdH');
61 $formula = $this->getDateFormat('Ymd');
64 $formula = $this->getDateFormat('Ym');
67 $formula = $this->getDateFormat('Y');
72 $this->query->addOrderBy(NULL, $formula, $this->options['order'], $this->tableAlias . '_' . $this->field . '_' . $this->options['granularity']);