Tải bản đầy đủ - 0 (trang)
Chapter 12. Date and Time Functions

Chapter 12. Date and Time Functions

Tải bản đầy đủ - 0trang

advisory firm) that tracks appointments and seminars in MySQL. For help locating

the appropriate function, see the next section or the index at the end of this book.

Date and Time Functions Grouped by Type

Following are lists of date and time functions, grouped according to their purpose:

to retrieve the date or time, to extract an element from a given date or time, or to

perform calculations on given dates or times.

Determining the Date or Time

CURDATE(  ), CURRENT_DATE(  ), CURRENT_TIME(  ), CURRENT_TIMESTAMP(  ), CURTIME(  ), LOCALTIME(  ), LOCALTIMESTAMP(  ), NOW(  ), SYSDATE(  ), UNIX_TIMESTAMP(  ), UTC_DATE(  ),

UTC_TIME(  ), UTC_TIMESTAMP(  ).

Extracting and Formatting the Date or Time

DATE(  ), DATE_FORMAT(  ), DAY(  ), DAYNAME(  ), DAYOFMONTH(  ), DAYOFWEEK(  ), DAYOFYEAR(  ), EXTRACT(  ), GET_FORMAT(  ), HOUR(  ), LAST_DAY(  ), MAKEDATE(  ), MAKETIME(  ),

MICROSECOND(  ), MINUTE(  ), MONTH(  ), MONTHNAME(  ), QUARTER(  ), SECOND(  ),

STR_TO_DATE(  ), TIME(  ), TIME_FORMAT(  ), TIMESTAMP(  ), WEEK(  ), WEEKDAY(  ), WEEKOFYEAR(  ), YEAR(  ), YEARWEEK(  ).

Calculating and Modifying the Date or Time

FROM_DAYS(  ), FROM_UNIXTIME(  ), PERIOD_ADD(  ), PERIOD_DIFF(  ), SEC_TO_TIME(  ),

SLEEP(  ), SUBDATE(  ), SUBTIME(  ), TIME_TO_SEC(  ), TIMEDIFF(  ), TIMESTAMPADD(  ), TIMESTAMPDIFF(  ), TO_DAYS(  ).

Date and Time Functions in Alphabetical Order

The rest of the chapter lists each function in alphabetical order.

This function adds the given interval of time to the date or time provided. This is a

synonym for DATE_ADD( ); see its definition later in this chapter for details and interval

types. The second, simpler syntax is available as of version 4.1 of MySQL. This shorthand

syntax does not work, though, with DATE_ADD( ). Here is an example:

UPDATE seminars

SET seminar_date = ADDDATE(seminar_date, INTERVAL 1 MONTH)

WHERE seminar_date = '2007-12-01';

264 | Chapter 12: Date and Time Functions

CONVERT_TZ(  )

UPDATE seminars

WHERE seminar_date = '2007-12-15';

The first SQL statement postpones a seminar that was scheduled for December 1, 2007

to a month later (January 1, 2008). The second statement postpones the seminar on

December 15 to December 22, seven days later.

SELECT NOW( ) AS Now,

ADDTIME(NOW( ), '1:00:00.00') AS 'Hour Later';

+---------------------+---------------------+

| Now

| Hour Later

|

+---------------------+---------------------+

| 2007-01-11 23:20:30 | 2007-01-12 00:20:30 |

+---------------------+---------------------+

Notice that the hour is increased by one, and because the time is near midnight, the

function causes the date to be altered by one day as well. To increase the date, add the

number of days before the time (separated by a space) like so:

SELECT NOW( ) AS Now,

ADDTIME(NOW( ), '30 0:0:0') AS 'Thirty Days Later';

+---------------------+---------------------+

| Now

| Thirty Days Later

|

+---------------------+---------------------+

| 2007-01-11 23:20:30 | 2007-02-10 23:20:30 |

+---------------------+---------------------+

CONVERT_TZ(  )

CONVERT_TZ(datetime, time_zone, time_zone)

This function converts a given date and time from the first time zone given to the second.

It requires time zone tables to be installed in the mysql database. If they are not already

timezones.html) to download the tables. Copy them into the mysql subdirectory of the

data directory of MySQL. Change the ownership to the mysql system user and change

the user permissions with system commands such as chown and chmod, and restart the

server. This function is available as of version 4.1.3 of MySQL. Here is an example:

SELECT NOW() AS 'New Orleans',

CONVERT_TZ(NOW(), 'US/Central', 'Europe/Rome')

e')

Chapter 12: Date and Time Functions | 265

Date and Time

Functions

This function returns the date and time for a given string or column (in time or datetime format), incremented by the time given as the second argument. If a negative number

is given, the time is subtracted. In this case, the function is the equivalent of SUBTIME(  ).

This function is available as of version 4.1.1 of MySQL. Here is an example:

CURDATE(  )

AS Milan;

+---------------------+---------------------+

| New Orleans

| Milan

|

+---------------------+---------------------|

| 2007-03-12 20:56:15 | 2007-03-13 02:56:15 |

+---------------------+---------------------+

This example retrieves the current time of the server, which for the sake of this example

is located in New Orleans, and converts this time to the time in Milan. Notice that we’re

using the named time zone of Europe/Rome. There’s isn’t a Europe/Milan choice. If a named

time zone that doesn’t exist is given, a NULL value is returned for that field. To find the

named time zones available, check the time_zone_name table in the mysql database:

SELECT Name

FROM mysql.time_zone_name

me

WHERE Name LIKE '%Europe%';

This will list all of the time zone names for Europe. From here, you can scan the list for

one in the same zone and close to the city that you want. Incidentally, if you’re converting

times with this function for tables you’ve locked, the time_zone_name table will need to

be locked, too.

CURDATE(  )

CURDATE( )

This function returns the current system date in yyyy-mm-dd format. It will return the date

in a yyyymmdd format (a numeric format) if it’s used as part of a numeric calculation. You

can use the function in SELECT statements as shown here, in INSERT and UPDATE statements

to set a value, or in a WHERE clause. CURDATE( ) is synonymous with CURRENT_DATE(  ); see

its definition next for more details. Here is an example:

SELECT CURDATE() AS Today,

CURDATE() + 1 AS Tomorrow;

ow;

+------------+----------+

| Today

| Tomorrow |

+------------+----------+

| 2007-01-15 | 20070116 |

+------------+----------+

Because the second use of the function here involves a numeric calculation, tomorrow’s

date is displayed without dashes. If you only want to convert a date to the numeric format,

just add 0. To keep the format the same, use this function together with a function such

CURRENT_DATE(  )

CURRENT_DATE( )

266 | Chapter 12: Date and Time Functions

CURRENT_TIMESTAMP(  )

This function returns the current date. The usual parentheses are not required. It’s synonymous with CURDATE(  ). You can use either in SELECT statements, as well as INSERT and

UPDATE statements to dynamically set values, or in WHERE clauses. Here is an example:

UPDATE appointment

SET appt_date = CURRENT_DATE( )

WHERE appt_id = '1250';

This statement changes the appointment date for a client who came in today

unexpectedly.

CURRENT_TIME(  )

This function returns the current time in hh:mm:ss format. It will return the time in the

hhmmss format (numeric format) if it’s used as part of a numeric calculation. The parentheses are not required. It’s synonymous with CURTIME(  ). Here is an example:

INSERT INTO appointments

(client_id, appt_date, start_time)

VALUES('1403', CURRENT_DATE( ), CURRENT_TIME);

In this example, we’re logging an unscheduled appointment that has just begun so that

we can bill the client later. Of course, it’s easy enough to use one datetime column with

the NOW( ) function for inserting data, and use other functions for extracting separate

components later.

CURRENT_TIMESTAMP(  )

CURRENT_TIMESTAMP( )

This function returns the current date and time in yyyy-mm-dd hh:mm:ss format. It will

return the time in a yyyymmddhhmmss format (numeric format) if it’s used as part of a

numeric calculation. Parentheses aren’t required. It’s a synonym of NOW(  ). Here is an

example:

SELECT CURRENT_TIMESTAMP() AS Now,

CURRENT_TIMESTAMP() + 10000 AS 'Hour Later';

r';

+---------------------+----------------+

| Now

| Hour Later

|

+---------------------+----------------+

| 2008-01-12 16:41:47 | 20080112174147 |

+---------------------+----------------+

By adding 10,000 to the current time, the hour is increased by 1 and the minutes and

seconds by 0 each, and the time is displayed in the second field without dashes. This is

in line with the yyyymmddhhmmss format involved in numeric calculations, with the

numbers right-justified.

Chapter 12: Date and Time Functions | 267

Date and Time

Functions

CURRENT_TIME( )

CURTIME(  )

CURTIME(  )

CURTIME( )

This function returns the current system time in hh:mm:ss format. It will return the time

in an hhmmss format (numeric format) if it’s used as part of a numeric calculation. This is

an alias for CURRENT_TIME(  ). Here is an example:

SELECT CURTIME() AS Now,

CURTIME() + 10000 AS 'Hour Later';

r';

+----------+------------+

| Now

| Hour Later |

+----------+------------+

| 16:35:43 |

163543 |

+----------+------------+

By adding 10,000 to the current time, this statement increases the hour by 1 and the

minutes and seconds by 0 each. This is in keeping with the yyyymmddhhmmss format

previously mentioned.

DATE(  )

DATE(expression)

This function returns the date from a given string, value, or expression that is submitted

in a date or datetime format. This function is available as of version 4.1.1 of MySQL.

Here is an example:

SELECT appointment, DATE(appointment)

FROM appointments

WHERE client_id = '8639' LIMIT 1;

+---------------------+-------------------+

| appointment

| DATE(appointment) |

+---------------------+-------------------+

| 2008-01-11 14:11:43 | 2008-01-11

|

+---------------------+-------------------+

In this SQL statement, the value of the appointment column, which is a DATETIME type

column, is shown first. The second field is the date extracted by the function from the

same column and row.

Using the date or datetime given, this function adds the number of intervals specified.

It’s fairly synonymous with the ADDDATE(  ) function. If none of the parameters include

datetime or time factors, the results will be returned in date format. Otherwise, the results

will be in datetime format. See Table 12-1 for a list of intervals permitted. Here is an

example:

268 | Chapter 12: Date and Time Functions

UPDATE appointments

SET appt_date = DATE_ADD(appt_date, INTERVAL 1 DAY)

WHERE appt_id='1202';

In this example, the appointment date is changed to its current value plus one additional

day to postpone the appointment by a day. If we changed the 1 to –1, MySQL would

subtract a day instead. This would make the function the equivalent of DATE_SUB( ).

If you leave out some numbers in the second argument, MySQL assumes that the leftmost

interval factors are 0 and are just not given. In the following example, although we’re

using the interval HOUR_SECOND, we’re not giving the number of hours and the function

still works—assuming we don’t mean 5 hours and 30 minutes later. MySQL assumes

here that we mean '00:05:30' and not '05:30:00':

+---------------------+---------------------+

| Now

| Later

|

+---------------------+---------------------+

| 2007-03-14 10:57:05 | 2007-03-14 11:02:35 |

+---------------------+---------------------+

When adding the intervals MONTH, YEAR, or YEAR_MONTH to a date, if the given date is valid

but the results would be an invalid date because it would be beyond the end of a month,

the results are adjusted to the end of the month:

AS 'One Month Later';

+-----------------+

| One Month Later |

+-----------------+

| 2009-02-28

|

+-----------------+

Table 12-1 shows the intervals that may be used and how the data should be ordered.

For interval values that require more than one factor, a delimiter is used and the data

must be enclosed in quotes. Other delimiters may be used besides those shown in the

table. For example, 'hh|mm|ss' could be used for HOUR_SECOND. In case you hadn’t noticed,

the names for intervals involving more than two time factors use the name of the first

and last factor (e.g., DAY_MINUTE and not DAY_HOUR_MINUTE). Keep that in mind when trying

to remember the correct interval.

Table 12-1. DATE_ADD( ) intervals and formats

INTERVAL

Format for given values

DAY

dd

DAY_HOUR

'dd hh'

DAY_MICROSECOND

'dd.nn'

DAY_MINUTE

'dd hh:mm'

DAY_SECOND

'dd hh:mm:ss'

Chapter 12: Date and Time Functions | 269

Date and Time

Functions

SELECT NOW( ) AS 'Now',

AS 'Later';

DATE_FORMAT(  )

INTERVAL

Format for given values

HOUR

hh

HOUR_MICROSECOND

'hh.nn'

HOUR_MINUTE

'hh:mm'

HOUR_SECOND

'hh:mm:ss'

MICROSECOND

nn

MINUTE

mm

MINUTE_MICROSECOND

'mm.nn'

MINUTE_SECOND

'mm:ss'

MONTH

mm

QUARTER

qq

SECOND

ss

SECOND_MICROSECOND

'ss.nn'

WEEK

ww

YEAR

yy

YEAR_MONTH

'yy-mm'

DATE_FORMAT(  )

DATE_FORMAT(date, 'format_code')

This function returns a date and time in a desired format, based on formatting codes

listed within quotes for the second argument of the function. Here is an example:

SELECT DATE_FORMAT(appointment, '%W - %M %e, %Y at %r')

AS 'Appointment'

FROM appointments

WHERE client_id = '8392'

AND appointment > CURDATE( );

+---------------------------------------+

| Appointment

|

+---------------------------------------+

| Monday - June 16, 2008 at 01:00:00 PM |

+---------------------------------------+

Using the formatting codes, we’re specifying in this example that we want the name of

the day of the week (%W) followed by a dash and then the date of the appointment in a

typical U.S. format (%M %e, %Y), with the month name and a comma after the day. We’re

ending with the word “at” followed by the full nonmilitary time (%r). The results are

returned as a binary string.

As of MySQL version 5.1.15, a string is returned along with the character set and collation

of the string, taken from the character_set_connection and the collation_connection

system variables. This allows the function to return non-ASCII characters. Here is an

example of this function:

270 | Chapter 12: Date and Time Functions

DATE_FORMAT(  )

SELECT NOW( ),

DATE_FORMAT(NOW( ), '%M') AS 'Month in Hebrew';

+---------------------+-----------------+

| Now

| Month in Hebrew |

+---------------------+-----------------+

| 2008-03-14 12:00:24 | ‫מרץ‬

|

+---------------------+-----------------+

Table 12-2 contains a list of all the formatting codes you can use with DATE_FORMAT( ).

You can also use these codes with TIME_FORMAT(  ) and EXTRACT(  ).

Table 12-2. DATE_FORMAT( ) format codes and resulting formats

Code

Description

%%

A literal '%'

Results

%a

Abbreviated weekday name

(Sun...Sat)

%b

Abbreviated month name

(Jan...Dec)

%c

Month, numeric

(1...12)

%d

Day of the month, numeric

(00...31)

%D

Day of the month with English suffix

(1st, 2nd, 3rd, etc.)

%e

Day of the month, numeric

(0...31)

%f

Microseconds, numeric

(000000...999999)

%h

Hour

(01...12)

%H

Hour

(00...23)

%i

Minutes, numeric

(00...59)

%I

Hour

(01...12)

%j

Day of the year

(001...366)

%k

Hour

(0...23)

%l

Hour

(1...12)

%m

Month, numeric

(01...12)

%M

Month name

(January...December)

%p

A.M. or P.M.

A.M. or P.M.

%r

Time, 12-hour

(hh:mm:ss [AM|PM])

%s

Seconds

(00...59)

%S

Seconds

(00...59)

%T

Time, 24-hour

(hh:mm:ss)

Chapter 12: Date and Time Functions | 271

Date and Time

Functions

In this example, of course, the client and server were set to display Hebrew characters.

Also, the server variable lc_time_names was set to Hebrew (he_IL) so as to return the

Hebrew word for March. See MySQL’s documentation page on MySQL Server Locale

Support (http://dev.mysql.com/doc/refman/5.1/en/locale-support.html) for a list of locale

values available for time names.

DATE_SUB(  )

Code

Description

Results

%u

Week, where Monday is the first day of the week

(0...52)

%U

Week, where Sunday is the first day of the week

(0...52)

%v

Week, where Monday is the first day of the week; used with %x

(1...53)

%V

Week, where Sunday is the first day of the week; used with %X

(1...53)

%w

Day of the week

(0=Sunday...6=Saturday)

%W

Weekday name

(Sunday...Saturday)

%x

Year for the week, where Monday is the first day of the week, numeric, four

digits; used with %v

(yyyy)

%X

Year for the week, where Sunday is the first day of the week, numeric, four

digits; used with %V

(yyyy)

%y

Year, numeric, two digits

(yy)

%Y

Year, numeric, four digits

(yyyy)

DATE_SUB(  )

DATE_SUB(date, INTERVAL number type)

Use this function to subtract from the results of a date or time data type column. See

Table 12-1, under the description of DATE_ADD(  ), for a list of interval types. Here is an

example of this function:

SELECT NOW( ) AS Today,

DATE_SUB(NOW( ), INTERVAL 1 DAY)

AS Yesterday;

+---------------------+---------------------+

| Today

| Yesterday

|

+---------------------+---------------------+

| 2007-05-14 14:26:54 | 2007-05-13 14:26:54 |

+---------------------+---------------------+

Notice in this example that the time remains unchanged, but the date was reduced by

one day. If you place a negative sign in front of the value 1, the reverse effect will occur,

giving a result of May 15 in this example. Any intervals that can be used with

DATE_ADD( ) can also be used with DATE_SUB( ).

DATEDIFF(  )

DATEDIFF(date, date)

This function returns the number of days of difference between the two dates given.

Although a parameter may be given in date and time format, only the dates are used for

determining the difference. This function is available as of version 4.1.1 of MySQL. Here

is an example:

SELECT CURDATE( ) AS Today,

DATEDIFF('2008-12-25', NOW( ))

AS 'Days to Christmas';

272 | Chapter 12: Date and Time Functions

DAYNAME(  )

+------------+-------------------+

| Today

| Days to Christmas |

+------------+-------------------+

| 2008-03-14 |

286 |

+------------+-------------------+

DAY(  )

DAY(date)

SELECT DAY('2008-12-15')

AS 'Day';

+-------+

| Day

|

+-------+

|

15 |

+-------+

This function is more meaningful when applied to a date column where the date is unknown before entering the SQL statement.

DAYNAME(  )

DAYNAME(date)

This function returns the name of the day for the date provided. As of MySQL version

5.1.15, the lc_time_names system variable will be consulted to determine the actual set

of names to use. Use the SET statement to change this variable. See MySQL’s documentation page on MySQL Server Locale Support (http://dev.mysql.com/doc/refman/5.1/en/

locale-support.html) for a list of locale values available for time names. Here is an example:

SELECT appt_date AS Appointment,

DAYNAME(appt_date) AS 'Day of Week'

FROM appointments

WHERE appt_id = '1439';

+---------------------+-------------+

| Date of Appointment | Day of Week |

+---------------------+-------------+

| 2008-03-14

| Friday

|

+---------------------+-------------+

SET lc_time_names = 'it_IT';

SELECT appt_date AS Appointment,

DAYNAME(appt_date) AS ''Day of Week in Italian'

FROM appointments

WHERE appt_id = '1439';

Chapter 12: Date and Time Functions | 273

Date and Time

Functions

This function returns the day of the month for a given date. It’s available as of version

4.1.1 of MySQL and is synonymous with the DAYOFMONTH(  ) function, described later.

Here is an example:

DAYOFMONTH(  )

+---------------------+------------------------+

| Date of Appointment | Day of Week in Italian |

+---------------------+------------------------+

| 2008-03-14

| venerdì

|

+---------------------+------------------------+

For this example, I have set character_set_client, character_set_connection, and

character_set_results to utf8, and set my terminal program to UTF-8 characters. Incidentally, the day of the week here is in lowercase because this is how it’s written in Italian.

DAYOFMONTH(  )

DAYOFMONTH(date)

This function returns the day of the month for the date given. If the day for the date is

beyond the end of the month (e.g., '2008-02-30'), the function returns NULL along with

a warning that can be retrieved with SHOW WARNINGS. Here is an example:

SELECT DAYOFMONTH('2008-02-28') AS 'A Good Day',

+------------+-----------+

| A Good Day | A Bad Day |

+------------+-----------+

|

28 |

NULL |

+------------+-----------+

1 row in set, 1 warning (0.00 sec)

SHOW WARNINGS;

+---------+------+--------------------------------------------------+

| Level

| Code | Message

|

+---------+------+--------------------------------------------------+

| Warning | 1292 | Truncated incorrect datetime value: '2008-02-30' |

+---------+------+--------------------------------------------------+

Prior to MySQL version 5.0.2, invalid dates such as this were permitted. The function

would have returned 30 for a value of '2008-02-30'. If you wish to allow invalid dates,

DAYOFWEEK(  )

DAYOFWEEK(date)

This function returns the numerical day of the week for a given date. Sunday returns a

value of 1, and Saturday returns a value of 7. Here is an example:

SELECT DAYOFWEEK('2008-11-03') AS 'Day of Week',

DAYNAME('2008-11-03') AS 'Name of Day';

+-------------+-------------+

| Day of Week | Name of Day |

+-------------+-------------+

274 | Chapter 12: Date and Time Functions

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 12. Date and Time Functions

Tải bản đầy đủ ngay(0 tr)

×