Recipe 6.4. Determining the Current Date or Time


Problem

What's today's date? What time is it?

Solution

Use the CURDATE⁠(⁠ ⁠ ⁠) , CURTIME⁠(⁠ ⁠ ⁠) or NOW⁠(⁠ ⁠ ⁠) functions to get values expressed with respect to the connection time zone. Use UTC_DATE⁠(⁠ ⁠ ⁠), UTC_TIME⁠(⁠ ⁠ ⁠), or UTC_TIMESTAMP⁠(⁠ ⁠ ⁠) for values in UTC time.

Discussion

Some applications need to know the current date or time, such as those that write log records tagged with the current date and time. This kind of information is also useful for date calculations that are performed in relation to the current date, such as finding the first (or last) day of the month, or determining the date for Wednesday of next week.

The current date and time are available through three functions. CURDATE⁠(⁠ ⁠ ⁠) and CURTIME⁠(⁠ ⁠ ⁠) return the date and time separately, and NOW⁠(⁠ ⁠ ⁠) returns them both as a date-and-time value:

mysql> SELECT CURDATE(), CURTIME(), NOW(); +------------+-----------+---------------------+ | CURDATE()  | CURTIME() | NOW()               | +------------+-----------+---------------------+ | 2006-06-03 | 09:41:50  | 2006-06-03 09:41:50 | +------------+-----------+---------------------+ 

CURRENT_DATE and CURRENT_TIME are synonyms for CURDATE⁠(⁠ ⁠ ⁠) and CURTIME⁠(⁠ ⁠ ⁠). CURRENT_TIMESTAMP is a synonym for NOW⁠(⁠ ⁠ ⁠).

The preceding functions return values for the client's connection time zone (Section 6.3). For values in UTC time, use the UTC_DATE⁠(⁠ ⁠ ⁠), UTC_TIME⁠(⁠ ⁠ ⁠), or UTC_TIMESTAMP⁠(⁠ ⁠ ⁠) functions instead.

To obtain subparts of these values (such as the current day of the month or current hour of the day), use the techniques discussed in Section 6.6.




MySQL Cookbook
MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2004
Pages: 375
Authors: Paul DuBois

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net