12.5. Date and Time Functions

MySQL 5.0

12.5. Date and Time Functions

This section describes the functions that can be used to manipulate temporal values. See Section 11.3, “Date and Time Types”, for a description of the range of values each date and time type has and the valid formats in which values may be specified.

Here is an example that uses date functions. The following query selects all rows with a value from within the last 30 days:

mysql>  FROM 
    -> ;

Note that 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 within a single query always produce the same result (for our purposes a single query also includes a call to a stored routine or trigger and all sub-routines called by that routine/trigger). This principle also applies to , , , , , and to any of their synonyms.

The , , , and functions return values in the connection's current time zone, which is available as the value of the system variable. In addition, assumes that its argument is a datetime value in the current time zone. See Section 5.11.8, “MySQL Server Time Zone Support”.

Some date functions can be used with “zero” dates or incomplete dates such as , whereas others cannot. Functions that extract parts of dates typically work with incomplete dates. For example:

mysql> 
        -> 0, 0

Other functions expect complete dates and return for incomplete dates. These include functions that perform date arithmetic or that map parts of dates to names. For example:

mysql> 
        -> NULL
mysql> 
        -> NULL
  • ,INTERVAL ), ,)

    When invoked with the form of the second argument, is a synonym for . The related function is a synonym for . For information on the argument, see the discussion for .

    mysql> 
            -> '1998-02-02'
    mysql> 
            -> '1998-02-02'
    

    When invoked with the form of the second argument, MySQL treats it as an integer number of days to be added to .

    mysql> 
            -> '1998-02-02'
    
  • ,)

    adds to and returns the result. is a time or datetime expression, and is a time expression.

    mysql> 
        ->                
            -> '1998-01-02 01:01:01.000001'
    mysql> 
            -> '03:00:01.999997'
    
  • ,,)

    converts a datetime value from the time zone given by to the time zone given by and returns the resulting value. Time zones are specified as described in Section 5.11.8, “MySQL Server Time Zone Support”. This function returns if the arguments are invalid.

    If the value falls out of the supported range of the type when converted fom to UTC, no conversion occurs. The range is described in Section 11.1.2, “Overview of Date and Time Types”.

    mysql> 
            -> '2004-01-01 13:00:00'
    mysql> 
            -> '2004-01-01 22:00:00'
    

    Note: To use named time zones such as or , the time zone tables must be properly set up. See Section 5.11.8, “MySQL Server Time Zone Support”, for instructions.

    If you intend to use while other tables are locked with , you must also lock the table.

  • Returns the current date as a value in or format, depending on whether the function is used in a string or numeric context.

    mysql> 
            -> '1997-12-15'
    mysql> 
            -> 19971215
    
  • ,

    and are synonyms for .

  • Returns the current time as a value in or format, depending on whether the function is used in a string or numeric context.

    mysql> 
            -> '23:50:26'
    mysql> 
            -> 235026
    
  • ,

    and are synonyms for .

  • ,

    and are synonyms for .

  • )

    Extracts the date part of the date or datetime expression .

    mysql> 
            -> '2003-12-31'
    
  • ,)

    returns expressed as a value in days from one date to the other. and are date or date-and-time expressions. Only the date parts of the values are used in the calculation.

    mysql> 
            -> 1
    mysql> 
            -> -31
    
  • ,INTERVAL ), ,INTERVAL )

    These functions perform date arithmetic. is a or value specifying the starting date. is an expression specifying the interval value to be added or subtracted from the starting date. is a string; it may start with a ‘’ for negative intervals. is a keyword indicating the units in which the expression should be interpreted.

    The keyword and the specifier are not case sensitive.

    The following table shows the expected form of the argument for each value.

    Value Expected Format

    The values and are available beginning with MySQL 5.0.0.

    MySQL allows any punctuation delimiter in the format. Those shown in the table are the suggested delimiters. If the argument is a value and your calculations involve only , , and parts (that is, no time parts), the result is a value. Otherwise, the result is a value.

    Date arithmetic also can be performed using together with the or operator:

     + INTERVAL  
     - INTERVAL  
    

    is allowed on either side of the operator if the expression on the other side is a date or datetime value. For the operator, is allowed only on the right side, because it makes no sense to subtract a date or datetime value from an interval.

    mysql> 
            -> '1998-01-01 00:00:00'
    mysql> 
            -> '1998-01-01'
    mysql> 
            -> '1997-12-31 23:59:59'
    mysql> 
        ->                 
            -> '1998-01-01 00:00:00'
    mysql> 
        ->                 
            -> '1998-01-01 23:59:59'
    mysql> 
        ->                 
            -> '1998-01-01 00:01:00'
    mysql> 
        ->                 
            -> '1997-12-30 22:58:59'
    mysql> 
        ->                 
            -> '1997-12-30 14:00:00'
    mysql> 
            -> '1997-12-02'
    mysql> 
        ->            
            -> '1993-01-01 00:00:01.000001'
    

    If you specify an interval value that is too short (does not include all the interval parts that would be expected from the keyword), MySQL assumes that you have left out the leftmost parts of the interval value. For example, if you specify a of , the value of is expected to have days, hours, minutes, and seconds parts. If you specify a value like , MySQL assumes that the days and hours parts are missing and the value represents minutes and seconds. In other words, is interpreted in such a way that it is equivalent to . This is analogous to the way that MySQL interprets values as representing elapsed time rather than as a time of day.

    If you add to or subtract from a date value something that contains a time part, the result is automatically converted to a datetime value:

    mysql> 
            -> '1999-01-02'
    mysql> 
            -> '1999-01-01 01:00:00'
    

    If you add , , or and the resulting date has a day that is larger than the maximum day for the new month, the day is adjusted to the maximum days in the new month:

    mysql> 
            -> '1998-02-28'
    

    Date arithmetic operations require complete dates and do not work with incomplete dates such as or badly malformed dates:

    mysql> 
            -> NULL
    mysql> 
            -> NULL
    
  • ,)

    Formats the value according to the string.

    The following specifiers may be used in the string. The ‘’ character is required before format specifier characters.

    Specifier Description
    Abbreviated weekday name (..)
    Abbreviated month name (..)
    Month, numeric (..)
    Day of the month with English suffix (, , , , …)
    Day of the month, numeric (..)
    Day of the month, numeric (..)
    Microseconds (..)
    Hour (..)
    Hour (..)
    Hour (..)
    Minutes, numeric (..)
    Day of year (..)
    Hour (..)
    Hour (..)
    Month name (..)
    Month, numeric (..)
    or
    Time, 12-hour ( followed by or )
    Seconds (..)
    Seconds (..)
    Time, 24-hour ()
    Week (..), where Sunday is the first day of the week
    Week (..), where Monday is the first day of the week
    Week (..), where Sunday is the first day of the week; used with
    Week (..), where Monday is the first day of the week; used with
    Weekday name (..)
    Day of the week (=Sunday..=Saturday)
    Year for the week where Sunday is the first day of the week, numeric, four digits; used with
    Year for the week, where Monday is the first day of the week, numeric, four digits; used with
    Year, numeric, four digits
    Year, numeric (two digits)
    A literal ‘’ character
    , for any ‘’ not listed above

    Ranges for the month and day specifiers begin with zero due to the fact that MySQL allows the storing of incomplete dates such as .

    mysql> 
            -> 'Saturday October 1997'
    mysql> 
            -> '22:23:00'
    mysql> 
                              '%D %y %a %d %m %b %j');
            -> '4th 97 Sat 04 10 Oct 277'
    mysql> 
                              '%H %k %I %r %T %S %w');
            -> '22 22 10 10:23:00 PM 22:23:00 00 6'
    mysql> 
            -> '1998 52'
    mysql> 
            -> '00'
    
  • )

    is a synonym for .

  • )

    Returns the name of the weekday for .

    mysql> 
            -> 'Thursday'
    
  • )

    Returns the day of the month for , in the range to .

    mysql> 
            -> 3
    
  • )

    Returns the weekday index for ( = Sunday, = Monday, …, = Saturday). These index values correspond to the ODBC standard.

    mysql> 
            -> 3
    
  • )

    Returns the day of the year for , in the range to .

    mysql> 
            -> 34
    
  • FROM )

    The function uses the same kinds of unit specifiers as or , but extracts parts from the date rather than performing date arithmetic.

    mysql> 
           -> 1999
    mysql> 
           -> 199907
    mysql> 
           -> 20102
    mysql> 
        ->                
            -> 123
    
  • )

    Given a day number , returns a value.

    mysql> 
            -> '1997-10-07'
    

    Use with caution on old dates. It is not intended for use with values that precede the advent of the Gregorian calendar (1582). See Section 12.6, “What Calendar Is Used By MySQL?”.

  • ), ,)

    Returns a representation of the argument as a value in or format, depending on whether the function is used in a string or numeric context. is an internal timestamp value such as is produced by the function.

    If is given, the result is formatted according to the string, which is used the same way as listed in the entry for the function.

    mysql> 
            -> '1997-10-04 22:23:00'
    mysql> 
            -> 19971004222300
    mysql> 
        ->                      
            -> '2003 6th August 06:22:58 2003'
    

    Note: If you use and to convert between values and Unix timestamp values, the conversion is lossy because the mapping is not one-to-one in both directions. For details, see the description of the function.

  • Returns a format string. This function is useful in combination with the and the functions.

    The possible values for the first and second arguments result in several possible format strings (for the specifiers used, see the table in the function description). ISO format refers to ISO 9075, not ISO 8601.

    Function Call Result

    can also be used as the first argument to , in which case the function returns the same values as for .

    mysql> 
            -> '03.10.2003'
    mysql> 
            -> '2003-10-31'
    
  • )

    Returns the hour for . The range of the return value is to for time-of-day values. However, the range of values actually is much larger, so can return values greater than .

    mysql> 
            -> 10
    mysql> 
            -> 272
    
  • )

    Takes a date or datetime value and returns the corresponding value for the last day of the month. Returns if the argument is invalid.

    mysql> 
            -> '2003-02-28'
    mysql> 
            -> '2004-02-29'
    mysql> 
            -> '2004-01-31'
    mysql> 
            -> NULL
    
  • ,

    and are synonyms for .

  • ,

    and are synonyms for .

  • ,)

    Returns a date, given year and day-of-year values. must be greater than 0 or the result is .

    mysql> 
            -> '2001-01-31', '2001-02-01'
    mysql> 
            -> '2001-12-31', '2004-12-30'
    mysql> 
            -> NULL
    
  • ,,)

    Returns a time value calculated from the , , and arguments.

    mysql> 
            -> '12:15:30'
    
  • )

    Returns the microseconds from the time or datetime expression as a number in the range from to .

    mysql> 
            -> 123456
    mysql> 
            -> 10
    
  • )

    Returns the minute for , in the range to .

    mysql> 
            -> 5
    
  • )

    Returns the month for , in the range to .

    mysql> 
            -> 2
    
  • )

    Returns the full name of the month for .

    mysql> 
            -> 'February'
    
  • Returns the current date and time as a value in or format, depending on whether the function is used in a string or numeric context.

    mysql> 
            -> '1997-12-15 23:50:26'
    mysql> 
            -> 19971215235026
    

    returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for , which returns the exact time at which it executes as of MySQL 5.0.13.

    mysql> 
    +---------------------+----------+---------------------+
    | NOW()               | SLEEP(2) | NOW()               |
    +---------------------+----------+---------------------+
    | 2006-04-12 13:47:36 |        0 | 2006-04-12 13:47:36 |
    +---------------------+----------+---------------------+
    
    mysql> 
    +---------------------+----------+---------------------+
    | SYSDATE()           | SLEEP(2) | SYSDATE()           |
    +---------------------+----------+---------------------+
    | 2006-04-12 13:47:44 |        0 | 2006-04-12 13:47:46 |
    +---------------------+----------+---------------------+
    

    See the description for for additional information about the differences between the two functions.

  • ,)

    Adds months to period (in the format or ). Returns a value in the format . Note that the period argument is not a date value.

    mysql> 
            -> 199803
    
  • ,)

    Returns the number of months between periods and . and should be in the format or . Note that the period arguments and are not date values.

    mysql> 
            -> 11
    
  • )

    Returns the quarter of the year for , in the range to .

    mysql> 
            -> 2
    
  • )

    Returns the second for , in the range to .

    mysql> 
            -> 3
    
  • )

    Returns the argument, converted to hours, minutes, and seconds, as a value in or format, depending on whether the function is used in a string or numeric context.

    mysql> 
            -> '00:39:38'
    mysql> 
            -> 3938
    
  • ,)

    This is the inverse of the function. It takes a string and a format string . returns a value if the format string contains both date and time parts, or a or value if the string contains only date or time parts.

    The date, time, or datetime values contained in should be given in the format indicated by . For the specifiers that can be used in , see the function description. If contains an illegal date, time, or datetime value, returns . Starting from MySQL 5.0.3, an illegal value also produces a warning.

    Range checking on the parts of date values is as described in Section 11.3.1, “The , , and Types”. This means, for example, that “zero” dates or dates with part values of 0 are allowed unless the SQL mode is set to disallow such values.

    mysql> 
            -> '0000-00-00'
    mysql> 
            -> '2004-04-31'
    
  • ,INTERVAL ), ,)

    When invoked with the form of the second argument, is a synonym for . For information on the argument, see the discussion for .

    mysql> 
            -> '1997-12-02'
    mysql> 
            -> '1997-12-02'
    

    The second form allows the use of an integer value for . In such cases, it is interpreted as the number of days to be subtracted from the date or datetime expression .

    mysql> 
            -> '1997-12-02 12:00:00'
    

    Note: You cannot use format to convert a year-week string to a date because the combination of a year and week does not uniquely identify a year and month if the week crosses a month boundary. To convert a year-week to a date, then you should also specify the weekday:

    mysql> 
            -> '2004-10-18'
    
  • ,)

    returns expressed as a value in the same format as . is a time or datetime expression, and is a time expression.

    mysql> 
            -> '1997-12-30 22:58:58.999997'
    mysql> 
            -> '-00:59:59.999999'
    
  • Returns the current date and time as a value in or format, depending on whether the function is used in a string or numeric context.

    As of MySQL 5.0.13, returns the time at which it executes. This differs from the behavior for , which returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, returns the time at which the routine or triggering statement began to execute.)

    mysql> 
    +---------------------+----------+---------------------+
    | NOW()               | SLEEP(2) | NOW()               |
    +---------------------+----------+---------------------+
    | 2006-04-12 13:47:36 |        0 | 2006-04-12 13:47:36 |
    +---------------------+----------+---------------------+
    
    mysql> 
    +---------------------+----------+---------------------+
    | SYSDATE()           | SLEEP(2) | SYSDATE()           |
    +---------------------+----------+---------------------+
    | 2006-04-12 13:47:44 |        0 | 2006-04-12 13:47:46 |
    +---------------------+----------+---------------------+
    

    In addition, the statement affects the value returned by but not by . This means that timestamp settings in the binary log have no effect on invocations of .

    Because can return different values even within the same statement, and is not affected by , it is non-deterministic and therefore unsafe for replication. If that is a problem, you can start the server with the option to cause to be an alias for .

  • )

    Extracts the time part of the time or datetime expression and returns it as a string.

    mysql> 
            -> '01:02:03'
    mysql> 
            -> '01:02:03.000123'
    
  • ,)

    returns expressed as a time value. and are time or date-and-time expressions, but both must be of the same type.

    mysql> 
        ->                 
            -> '-00:00:00.000001'
    mysql> 
        ->                 
            -> '46:58:57.999999'
    
  • ), ,)

    With a single argument, this function returns the date or datetime expression as a datetime value. With two arguments, it adds the time expression to the date or datetime expression and returns the result as a datetime value.

    mysql> 
            -> '2003-12-31 00:00:00'
    mysql> 
            -> '2004-01-01 00:00:00'
    
  • ,,)

    Adds the integer expression to the date or datetime expression . The unit for is given by the argument, which should be one of the following values: , , , , , , , , or .

    The value may be specified using one of keywords as shown, or with a prefix of . For example, and both are legal.

    mysql> 
            -> '2003-01-02 00:01:00'
    mysql> 
            -> '2003-01-09'
    

    is available as of MySQL 5.0.0.

  • ,,)

    Returns the integer difference between the date or datetime expressions and . The unit for the result is given by the argument. The legal values for are the same as those listed in the description of the function.

    mysql> 
            -> 3
    mysql> 
            -> -1
    

    is available as of MySQL 5.0.0.

  • ,)

    This is used like the function, but the string may contain format specifiers only for hours, minutes, and seconds. Other specifiers produce a value or .

    If the value contains an hour part that is greater than , the and hour format specifiers produce a value larger than the usual range of . The other hour format specifiers produce the hour value modulo 12.

    mysql> 
            -> '100 100 04 04 4'
    
  • )

    Returns the argument, converted to seconds.

    mysql> 
            -> 80580
    mysql> 
            -> 2378
    
  • )

    Given a date , returns a day number (the number of days since year 0).

    mysql> 
            -> 728779
    mysql> 
            -> 729669
    

    is not intended for use with values that precede the advent of the Gregorian calendar (1582), because it does not take into account the days that were lost when the calendar was changed. For dates before 1582 (and possibly a later year in other locales), results from this function are not reliable. See Section 12.6, “What Calendar Is Used By MySQL?”, for details.

    Remember that MySQL converts two-digit year values in dates to four-digit form using the rules in Section 11.3, “Date and Time Types”. For example, and are seen as identical dates:

    mysql> 
            -> 729669, 729669
    
  • , )

    If called with no argument, returns a Unix timestamp (seconds since UTC) as an unsigned integer. If is called with a argument, it returns the value of the argument as seconds since UTC. may be a string, a string, a , or a number in the format or . The server interprets as a value in the current time zone and converts it to an internal value in UTC. Clients can set their time zone as described in Section 5.11.8, “MySQL Server Time Zone Support”.

    mysql> 
            -> 882226357
    mysql> 
            -> 875996580
    

    When is used on a column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion. If you pass an out-of-range date to , it returns .

    Note: If you use and to convert between values and Unix timestamp values, the conversion is lossy because the mapping is not one-to-one in both directions. For example, due to conventions for local time zone changes, it is possible for two to map two values to the same Unix timestamp value. will map that value back to only one of the original values. Here is an example, using values in the time zone:

    mysql> 
    +---------------------------------------+
    | UNIX_TIMESTAMP('2005-03-27 03:00:00') |
    +---------------------------------------+
    |                            1111885200 |
    +---------------------------------------+
    mysql> 
    +---------------------------------------+
    | UNIX_TIMESTAMP('2005-03-27 02:00:00') |
    +---------------------------------------+
    |                            1111885200 |
    +---------------------------------------+
    mysql> 
    +---------------------------+
    | FROM_UNIXTIME(1111885200) |
    +---------------------------+
    | 2005-03-27 03:00:00       |
    +---------------------------+
    

    If you want to subtract columns, you might want to cast the result to signed integers. See Section 12.8, “Cast Functions and Operators”.

  • ,

    Returns the current UTC date as a value in or format, depending on whether the function is used in a string or numeric context.

    mysql> 
            -> '2003-08-14', 20030814
    
  • ,

    Returns the current UTC time as a value in or format, depending on whether the function is used in a string or numeric context.

    mysql> 
            -> '18:07:53', 180753
    
  • ,

    Returns the current UTC date and time as a value in or format, depending on whether the function is used in a string or numeric context.

    mysql> 
            -> '2003-08-14 18:08:04', 20030814180804
    
  • [,])

    This function returns the week number for . The two-argument form of allows you to specify whether the week starts on Sunday or Monday and whether the return value should be in the range from to or from to . If the argument is omitted, the value of the system variable is used. See Section 5.2.2, “Server System Variables”.

    The following table describes how the argument works.

      First day    
    Mode of week Range Week 1 is the first week …
    0 Sunday 0-53 with a Sunday in this year
    1 Monday 0-53 with more than 3 days this year
    2 Sunday 1-53 with a Sunday in this year
    3 Monday 1-53 with more than 3 days this year
    4 Sunday 0-53 with more than 3 days this year
    5 Monday 0-53 with a Monday in this year
    6 Sunday 1-53 with more than 3 days this year
    7 Monday 1-53 with a Monday in this year
    mysql> 
            -> 7
    mysql> 
            -> 7
    mysql> 
            -> 8
    mysql> 
            -> 53
    

    Note that if a date falls in the last week of the previous year, MySQL returns if you do not use , , , or as the optional argument:

    mysql> 
            -> 2000, 0
    

    One might argue that MySQL should return for the function, because the given date actually occurs in the 52nd week of 1999. We decided to return instead because we want the function to return “the week number in the given year.” This makes use of the function reliable when combined with other functions that extract a date part from a date.

    If you would prefer the result to be evaluated with respect to the year that contains the first day of the week for the given date, use , , , or as the optional argument.

    mysql> 
            -> 52
    

    Alternatively, use the function:

    mysql> 
            -> 199952
    mysql> 
            -> '52'
    
  • )

    Returns the weekday index for ( = Monday, = Tuesday, … = Sunday).

    mysql> 
            -> 1
    mysql> 
            -> 2
    
  • )

    Returns the calendar week of the date as a number in the range from to . is a compatibility function that is equivalent to ,3).

    mysql> 
            -> 8
    
  • )

    Returns the year for , in the range to , or for the “zero” date.

    mysql> 
            -> 1998
    
  • ), ,)

    Returns year and week for a date. The argument works exactly like the argument to . The year in the result may be different from the year in the date argument for the first and the last week of the year.

    mysql> 
            -> 198653
    

    Note that the week number is different from what the function would return () for optional arguments or , as then returns the week in the context of the given year.