You are here

public function date_sql_handler::sql_date_math in Date 7.3

Same name and namespace in other branches
  1. 5.2 date_api_sql.inc \date_sql_handler::sql_date_math()
  2. 6.2 date_api_sql.inc \date_sql_handler::sql_date_math()
  3. 7 date_api/date_api_sql.inc \date_sql_handler::sql_date_math()
  4. 7.2 date_api/date_api_sql.inc \date_sql_handler::sql_date_math()

Adjusts a field value by time interval.

Parameters

string $field: The field to be adjusted.

string $direction: Either ADD or SUB.

int $count: The number of values to adjust.

string $granularity: The granularity of the adjustment, should be singular, like SECOND, MINUTE, DAY, HOUR.

File

date_api/date_api_sql.inc, line 326
SQL helper for Date API.

Class

date_sql_handler
A class to manipulate date SQL.

Code

public function sql_date_math($field, $direction, $count, $granularity) {
  $granularity = strtoupper($granularity);
  switch ($this->db_type) {
    case 'mysql':
      switch ($direction) {
        case 'ADD':
          return "DATE_ADD(CAST({$field} AS DATETIME), INTERVAL {$count} {$granularity})";
        case 'SUB':
          return "DATE_SUB(CAST({$field} AS DATETIME), INTERVAL {$count} {$granularity})";
      }
    case 'pgsql':
      $granularity .= 'S';
      switch ($direction) {
        case 'ADD':
          return "({$field} + INTERVAL '{$count} {$granularity}')";
        case 'SUB':
          return "({$field} - INTERVAL '{$count} {$granularity}')";
      }
    case 'sqlite':
      $granularity .= 'S';
      switch ($direction) {
        case 'ADD':
          return "datetime({$field}, '+{$count} {$granularity}')";
        case 'SUB':
          return "datetime({$field}, '-{$count} {$granularity}')";
      }
  }
  return $field;
}