views:

31

answers:

3

I need to calculate the weeks out from a date in my MySQL select statement. There is a date column in one of the tables, and I need to calculate how many weeks away the date is.

SELECT EventDate, (calculation) AS WeeksOut FROM Events;

Example:

  • 6 days away, weeks out = 0
  • 7 days away, weeks out = 1
  • 13 days away, weeks out = 1
  • 14 days away, weeks out = 2
A: 

See Week()

RC
+4  A: 

Use the DATEDIFF function:

ROUND(DATEDIFF(end_date, start_date)/7, 0) AS weeksout

The problem with WEEKS is that it won't return correct results for dates that cross over January 1st.

OMG Ponies
+1 Good point on the new year issue, hadn't thought of that...
Abe Miessler
A: 

Here's a simple way to do it:

SELECT EventDate, (week(EventDate) - week(curdate())) AS WeeksOut FROM Events;

Example:

mysql> select week('2010-11-18') - week ('2010-10-18');
+------------------------------------------+
| week('2010-11-18') - week ('2010-10-18') |
+------------------------------------------+
|                                        4 |
+------------------------------------------+
1 row in set (0.00 sec)

Another option is calculate the interval in days and divide by 7:

SELECT EventDate, datediff(EventDate,curdate())/7 AS WeeksOut FROM Events;

Example:

mysql> select datediff('2010-11-18' , '2010-10-18') / 7;
+-------------------------------------------+
| datediff('2010-11-18' , '2010-10-18') / 7 |
+-------------------------------------------+
|                                    4.4286 |
+-------------------------------------------+
1 row in set (0.00 sec)
Ike Walker