Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: How to calculate weeks out from a specific date?

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
like image 746
Andrew Avatar asked Oct 18 '10 14:10

Andrew


People also ask

How many weeks are there in a year in MySQL?

Every year has around 52 to 53 weeks. Suppose you want to find out the week number of a particular date. For this purpose, MySQL provides us with the WEEK () function. The WEEK () function is used to return the week number for a specified date. It is generally a number from 0 to 53.

What is the first day of the week in MySQL?

For mode value ‘1’, the first day of the week is a Monday, and the Week 1 is the first week with 4 or more days in that year. The value returned by MySQL WEEK () is a value between 0 to 53.

How to do advanced date calculation in MySQL?

Date calculation. In this page, we have shown an advanced MySQL date calculation using the following functions : CURDATE() function which returns the current date of the computer, YEAR() function which returns the year of the specified date, MONTH() function which returns the month of the specified date, DAY() function which returns the day...

How to calculate the number of weeks in a year?

So for a year we often has 365 / 7 = 52 weeks that range from 1 to 52. To check whether a particular date belongs to which week number, you use the WEEK function as follows: The WEEK function accepts two arguments: date is the date that you want to get a week number. mode is an optional argument that determines the logic of week number calculation.


2 Answers

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.

The 0 is the number of decimal places to use in the ROUND function.

like image 62
OMG Ponies Avatar answered Sep 23 '22 17:09

OMG Ponies


In order to get past the whole "New Year" issue and you still want to use WEEK(), I found the following method quite effective.

SELECT 
    YEAR(end_date)*52+WEEK(end_date)
    - YEAR(start_date)*52 - WEEK(start_date) as weeks_out
FROM
    events;

The difference with this method (as opposed to the DATEDIFF method) is that it is aligned with the week. So today (which is Monday) and last Friday would return 1 using this method, but would return 0 with the DATEDIFF method

like image 22
Kirk Backus Avatar answered Sep 20 '22 17:09

Kirk Backus