Tips for Manipulating dates in MySQL.

February 6th, 2009 by Tim Leave a reply »

Bypassing PHP to manipulate dates.

I despise working with dates in PHP. So much so that I now manipulate my dates using MySQL so I have everything I want in a php variable delivered by one SQL statement. Adding, subtracting, calculating differences and performing other date manipulations can be a pain in PHP. If you have a database connection running in your application it can be much quicker and easier to read if you work with dates in your SQL. The key to this is that you don’t need to work with tables and records in a database to use SQL. Many of the examples below don’t make queries against any record sets and yet they return valid results.

Adding or subtracting time from dates in MySQL.

Often when I work with PayPal subscriptions I have to update a users renewal date on my database by say 6 months etc. MySQL has a very simple way of dealing with this in the INTERVAL statement. For example to add 1 month to todays date you can do this:

SELECT NOW() + INTERVAL 1 MONTH

Conversely to subtract 5 days from the current date do the following:

SELECT NOW() – 5 DAY

Let’s say you want to add a year to a subscribtion by updating the field renewal_date:

UPDATE users SET renewal date = renewal_date + INTERVAL 1 YEAR

There are good few timescales that can be used with INTERVAL including SECOND, MINUTE, DAY, WEEK, MONTH, YEAR.

Formatting dates in MySQL.

MySQL uses the American date format of YYY-MM-DD. I don’t care for it any more than I care for using the property “color” in CSS, but I can’t change it. To change the way a date appears in MySQL, the true power-tool is DATE_FORMAT. This takes 2 arguments: the date you want to format and the new appearance of this date.

For instance:

SELECT DATE_FORMAT(NOW(),’%d/%m/%Y’) as display_date

Would return something like:

display_date=>27/03/2007

Of  course, in this instance PHP’s date() function would be just as easy to use, but when you are dealing with a date from a field DATE_FORMAT is irreplaceable.

A full list of date formatting codes is avaliable in the MySQL Reference Manual.

Calculating the difference between two dates in MySQL

Another simple task when you use the DATEDIFF function. The first argument is the start date, and the second is the date you want to calcuate the difference to or from:

SELECT DATEDIFF(”2007-12-31″,”2007-12-30″)

Gives us a value of 1.

SELECT DATEDIFF(”2007-12-28″,”2007-12-31″)

Give us a value of -3

The results of DATEDIFF are given in days.

Selecting parts of a date in MySQL.

You may want to return a part of a date such as the day that a specific date falls on, or the hour that a task is due on a certain day. There are a number of functions to get specific parts of a date. All you have to do is feed them with a date:

SELECT DAYNAME(”2004-02-13″)

Would return “Friday”

Other useful functions for extracting date parts are:

DAY() – returns the day of the month (e.g 13)
MONTH() – returns the month name
YEAR() – returns the year
WEEK() – returns the week number

Digging Deeper

All the above are very simple techniques that will make your day to day use of dates in your coding more pleasant. However, they are the tip of the iceberg in MySQL date manipulation and should you wish to go further, the MySQL reference manual has a comprehensive section on date functions.

Share it:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • LinkedIn
  • Reddit
  • Netvibes
  • Twitthis
  • email
Advertisement

2 comments

  1. Jean says:

    Hi
    Wonder if you can help me with formating a date using a mysql_fetch_array. Following your instructions above and am to MySQL & PHP . I get a “supplied argument is not a valid MySQL result resource error” and I think that I am not getting the right syntax.
    I have field joindate which is saved as now() and I endeavouring to change it to %a %d %b %Y. Here is the code:
    $list_count = mysql_fetch_array(mysql_query(”SELECT COUNT(*) FROM $list WHERE userid=’$f[id]‘,DATE_FORMAT(NOW(),’%a %d %b %Y’) as joindate;” ));

    Appreciate your help

  2. dinesh says:

    Wonder if you can help me with formating a date using a mysql_fetch_array. Following your instructions above and am to MySQL & PHP . I get a “supplied argument is not a valid MySQL result resource error” and I think that I am not getting the right syntax.
    I have field joindate which is saved as now() and I endeavouring to change it to %a %d %b %Y. Here is the code:
    $list_count = mysql_fetch_array(mysql_query(”SELECT COUNT(*) FROM $list WHERE userid=’$f[id]‘,DATE_FORMAT(NOW(),’%a %d %b %Y’) as joindate;” ));

    Appreciate your help

Leave a Reply