6.3.4 Функции даты и времени
Описание диапазона величин для каждого типа и возможные форматы представления даты и времени приведены в разделе section 6.2.2 Типы данных даты и времени .
Ниже представлен пример, в котором используются функции даты. Приведенный запрос выбирает все записи с величиной date_col в течение последних 30 дней:
DAYOFWEEK(date) Возвращает индекс дня недели для аргумента date (1 = воскресенье, 2 = понедельник. 7 = суббота). Эти индексные величины соответствуют стандарту ODBC: WEEKDAY(date) Возвращает индекс дня недели для аргумента date (0 =понедельник, 1 = вторник. 6 = воскресенье): DAYOFMONTH(date) Возвращает порядковый номер дня месяца для аргумента date в диапазоне от 1 до 31: DAYOFYEAR(date) Возвращает порядковый номер дня года для аргумента date в диапазоне от 1 до 366: MONTH(date) Возвращает порядковый номер месяца в году для аргумента date в диапазоне от 1 до 12: DAYNAME(date) Возвращает название дня недели для аргумента date. MONTHNAME(date) Возвращает название месяца для аргумента date. QUARTER(date) Возвращает номер квартала года для аргумента date в диапазоне от 1 до 4: WEEK(date) WEEK(date, first) При наличии одного аргумента возвращает порядковый номер недели в году для date в диапазоне от 0 до 53 (да, возможно начало 53-й недели) для регионов, где воскресенье считается первым днем недели. Форма WEEK() с двумя аргументами позволяет уточнить, с какого дня начинается неделя - с воскресенья или с понедельника. Неделя начинается с воскресенья, если второй аргумент равен 0, и с понедельника - если 1: Примечание: в версии 4.0 функция WEEK(#,0) была изменена с целью соответствия календарю США. YEAR(date) Возвращает год для аргумента date в диапазоне от 1000 до 9999: YEARWEEK(date) YEARWEEK(date, first) Возвращает год и неделю для аргумента date. Второй аргумент в данной функции работает подобно второму аргументу в функции WEEK(). Следует учитывать, что год может отличаться от указанного в аргументе date для первой и последней недель года: HOUR(time) Возвращает час для аргумента time в диапазоне от 0 до 23: MINUTE(time) Возвращает количество минут для аргумента time в диапазоне от 0 до 59: SECOND(time) Возвращает количество секунд для аргумента time в диапазоне от 0 до 59: PERIOD_ADD(P, N) Добавляет N месяцев к периоду P (в формате YYMM или YYYYMM ). Возвращает величину в формате YYYYMM. Следует учитывать, что аргумент периода P не является значением даты: PERIOD_DIFF(P1,P2) Возвращает количество месяцев между периодами P1 и P2. P1 и P2 должны быть в формате YYMM или YYYYMM. Следует учитывать, что аргументы периода P1 и P2 не являются значениями даты: DATE_ADD(date, INTERVAL expr type) DATE_SUB(date, INTERVAL expr type) ADDDATE(date, INTERVAL expr type) SUBDATE(date, INTERVAL expr type) Данные функции производят арифметические действия над датами. Обе являются нововведением версии MySQL 3.22. Функции ADDDATE() и SUBDATE() - синонимы для DATE_ADD() и DATE_SUB(). В версии MySQL 3.23 вместо функций DATE_ADD() и DATE_SUB() можно использовать операторы + и -. если выражение с правой стороны представляет собой столбец типа DATE или DATETIME (см. пример ниже). Аргумент date является величиной типа DATETIME или DATE. задающей начальную дату. Выражение expr задает величину интервала, который следует добавить к начальной дате или вычесть из начальной даты. Выражение expr представляет собой строку, которая может начинаться с - для отрицательных значений интервалов. Ключевое слово type показывает, каким образом необходимо интерпретировать данное выражение. Вспомогательная функция EXTRACT(type FROM date) возвращает интервал указанного типа ( type ) из значения даты. В следующей таблице показана взаимосвязь аргументов type и expr :
Ожидаемый формат expr
Format Date Fields Using MySQL DATE_FORMAT()
I use MySQL DATE and DATETIME fields almost as much as VARCHAR fields. I use them mostly to track record creation, record updates, and record expiration dates. The default date format in MYSQL is:
When I pull this information into the page, I want to show the date in human-readable format. That's where MySQL's DATE_FORMAT functionality comes in. DATE_FORMAT allows me to format the date in any manner you'd like.
Recent Features
CSS Gradients
Incredible Demos
MooTools Flashlight Effect
Discussion
Juan Gotti
This is a great post, Thanks.
Amiro. CMS 6. Что нового?
отвечающее потребностям разработчиков и потребителей, совместимое с предыдущими версиями, уже проверенное временем и обладающее богатым функционалом.
гипермодуль-конфигурация-экземпляр. Максимально возможное количество альтернатив реализации исходя из стоящей перед разработчиком задачи.
Теперь Amiro. CMS это платформа с открытым кодом, дающая широчайшие возможности разработчикам для расширения функционала под потребности любых проектов.
MySQL DATE_FORMAT Function
Summary . in this tutorial, you will learn how to use theВ MySQL DATE_FORMATВ function to format a date value based on a specific format.
Introduction to MySQL DATE_FORMAT function
The В DATE_FORMAT function accepts two arguments:
date. is a valid date value that you want to format
format. is a format string that consists of predefined specifiers. Each specifier is preceded by a percentage character ( % ). See the table below for a list of predefined specifiers.
The following table illustrates the specifiers and their meanings that you can use to construct date format string:
Return the year and week
Here is an example that uses date functions. The following query selects all rows with a date_col value from within the last 30 days:
The query also selects rows with dates that lie in the future.
Functions that expect date values usually accept datetime values and ignore the time part. Functions that expect time values usually accept datetime values and ignore the date part.
Functions that return the current date or time each are evaluated only once per query at the start of query execution. This means that multiple references to a function such as NOW() within a single query always produce the same result. This principle also applies to CURDATE(). CURTIME(). UTC_DATE(). UTC_TIME(). UTC_TIMESTAMP(). and to any of their synonyms.
Beginning with MySQL 4.1.3, the CURRENT_TIMESTAMP(). CURRENT_TIME(). CURRENT_DATE(). and FROM_UNIXTIME() functions return values in the connection's current time zone, which is available as the value of the time_zone system variable. In addition, UNIX_TIMESTAMP() assumes that its argument is a datetime value in the current time zone. See Section 9.7, “MySQL Server Time Zone Support” .
Some date functions can be used with “ zero ” dates or incomplete dates such as '2001-11-00'. whereas others cannot. Functions that extract parts of dates typically work with incomplete dates and thus can return 0 when you might otherwise expect a nonzero value. For example:
Other functions expect complete dates and return NULL for incomplete dates. These include functions that perform date arithmetic or that map parts of dates to names. For example:
When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD(). The related function SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD() .
As of MySQL 4.1.1, the second syntax is permitted. When invoked with the days form of the second argument, MySQL treats it as an integer number of days to be added to expr .
ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or datetime expression, and expr2 is a time expression.
ADDTIME() was added in MySQL 4.1.1.
CONVERT_TZ() converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. Time zones are specified as described in Section 9.7, “MySQL Server Time Zone Support”. This function returns NULL if the arguments are invalid.
If the value falls out of the supported range of the TIMESTAMP type when converted from from_tz to UTC, no conversion occurs. The TIMESTAMP range is described in Section 10.1.2, “Date and Time Type Overview” .
To use named time zones such as 'MET' or 'Europe/Moscow'. the time zone tables must be properly set up. See Section 9.7, “MySQL Server Time Zone Support”. for instructions.
CONVERT_TZ() was added in MySQL 4.1.3.
If you intend to use CONVERT_TZ() while other tables are locked with LOCK TABLES. you must also lock the mysql. time_zone_name table.
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.
Returns the current time as a value in 'HH:MM:SS' or HHMMSS. uuuuuu format, depending on whether the function is used in a string or numeric context. (There is no. uuuuuu part before MySQL 4.1.13.) The value is expressed in the current time zone.
Return the year and week
Here is an example that uses date functions. The following query selects all rows with a date_col value from within the last 30 days:
The query also selects rows with dates that lie in the future.
Functions that expect date values usually accept datetime values and ignore the time part. Functions that expect time values usually accept datetime values and ignore the date part.
Functions that return the current date or time each are evaluated only once per query at the start of query execution. This means that multiple references to a function such as NOW() within a single query always produce the same result. (For our purposes, a single query also includes a call to a stored program (stored routine, trigger, or event) and all subprograms called by that program.) This principle also applies to CURDATE(). CURTIME(). UTC_DATE(). UTC_TIME(). UTC_TIMESTAMP(). and to any of their synonyms.
The CURRENT_TIMESTAMP(). CURRENT_TIME(). CURRENT_DATE(). and FROM_UNIXTIME() functions return values in the connection's current time zone, which is available as the value of the time_zone system variable. In addition, UNIX_TIMESTAMP() assumes that its argument is a datetime value in the current time zone. See Section 10.6, “MySQL Server Time Zone Support” .
Some date functions can be used with “ zero ” dates or incomplete dates such as '2001-11-00'. whereas others cannot. Functions that extract parts of dates typically work with incomplete dates and thus can return 0 when you might otherwise expect a nonzero value. For example:
Other functions expect complete dates and return NULL for incomplete dates. These include functions that perform date arithmetic or that map parts of dates to names. For example:
From MySQL 5.1.59 to 5.1.61, a change in handling of a date-related assertion caused several functions to become more strict when passed a DATE() function value as their argument and reject incomplete dates with a day part of zero. These functions are affected: CONVERT_TZ(). DATE_ADD(). DATE_SUB(). DAYOFYEAR(). LAST_DAY(). TIMESTAMPDIFF(). TO_DAYS(). TO_SECONDS(). WEEK(). WEEKDAY(). WEEKOFYEAR(). YEARWEEK(). Because this changes date-handling behavior in General Availability-status series MySQL 5.1, the change was reverted in 5.1.62.
When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD(). The related function SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD() .
When invoked with the days form of the second argument, MySQL treats it as an integer number of days to be added to expr .
ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or datetime expression, and expr2 is a time expression.
CONVERT_TZ() converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. Time zones are specified as described in Section 10.6, “MySQL Server Time Zone Support”. This function returns NULL if the arguments are invalid.
If the value falls out of the supported range of the TIMESTAMP type when converted from from_tz to UTC, no conversion occurs. The TIMESTAMP range is described in Section 11.1.2, “Date and Time Type Overview” .
To use named time zones such as 'MET' or 'Europe/Moscow'. the time zone tables must be properly set up. See Section 10.6, “MySQL Server Time Zone Support”. for instructions.
Before MySQL 5.1.17, if you intend to use CONVERT_TZ() while other tables are locked with LOCK TABLES. you must also lock the mysql. time_zone_name table. See Section 13.3.5, “LOCK TABLES and UNLOCK TABLES Syntax” .
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.
No comments:
Post a Comment