You are here

public function SqliteDateSql::getDateFormat in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/views/src/Plugin/views/query/SqliteDateSql.php \Drupal\views\Plugin\views\query\SqliteDateSql::getDateFormat()

Creates a native database date formatting.

Parameters

string $field: An appropriate query expression pointing to the date field.

string $format: A format string for the result. For example: 'Y-m-d H:i:s'.

Return value

string A string representing the field formatted as a date as specified by $format.

Overrides DateSqlInterface::getDateFormat

File

core/modules/views/src/Plugin/views/query/SqliteDateSql.php, line 83

Class

SqliteDateSql
SQLite-specific date handling.

Namespace

Drupal\views\Plugin\views\query

Code

public function getDateFormat($field, $format) {
  $format = strtr($format, static::$replace);

  // SQLite does not have an ISO week substitution string, so it needs special
  // handling.
  // @see http://wikipedia.org/wiki/ISO_week_date#Calculation
  // @see http://stackoverflow.com/a/15511864/1499564
  if ($format === '%W') {
    $expression = "((strftime('%j', date(strftime('%Y-%m-%d', {$field}, 'unixepoch'), '-3 days', 'weekday 4')) - 1) / 7 + 1)";
  }
  else {
    $expression = "strftime('{$format}', {$field}, 'unixepoch')";
  }

  // The expression yields a string, but the comparison value is an integer in
  // case the comparison value is a float, integer, or numeric. All of the
  // above SQLite format tokens only produce integers. However, the given
  // $format may contain 'Y-m-d', which results in a string.
  // @see \Drupal\Core\Database\Driver\sqlite\Connection::expandArguments()
  // @see http://www.sqlite.org/lang_datefunc.html
  // @see http://www.sqlite.org/lang_expr.html#castexpr
  if (preg_match('/^(?:%\\w)+$/', $format)) {
    $expression = "CAST({$expression} AS NUMERIC)";
  }
  return $expression;
}