tags:

views:

1427

answers:

4

I'm using DAYOFWEEK() function in MySQL which returns 1 for sunday. But in my country the week starts with monday, not sunday. Is there any chance to get dayofweek from MySQL formated like: (1 - Monday, 2 - Tuesday, ...) ?

A: 

How about subtracting one and changing Sunday

IF(DAYOFWEEK() = 1, 7, DAYOFWEEK() - 1)

Of course you would have to do this for every query.

Justin Giboney
1=Sunday is ODBC standard, so it would have to be in query I think.
Al
Why the downvote?
John Kugelman
This works, but it is too much complicated.
picca
A: 

Could write a udf and take a value to tell it which day of the week should be 1 would look like this (drawing on answer from John to use MOD instead of CASE):

DROP FUNCTION IF EXISTS `reporting`.`udfDayOfWeek`;
DELIMITER |
CREATE FUNCTION `reporting`.`udfDayOfWeek` (
  _date DATETIME,
  _firstDay TINYINT
) RETURNS tinyint(4)
FUNCTION_BLOCK: BEGIN
  DECLARE _dayOfWeek, _offset TINYINT;
  SET _offset = 8 - _firstDay;
  SET _dayOfWeek = (DAYOFWEEK(_date) + _offset) MOD 7;
  IF _dayOfWeek = 0 THEN
    SET _dayOfWeek = 7;
  END IF;
  RETURN _dayOfWeek;
END FUNCTION_BLOCK

To call this function to give you the current day of week value when your week starts on a Tuesday for instance, you'd call:

SELECT udfDayOfWeek(NOW(), 3);

Nice thing about having it as a udf is you could also call it on a result set field like this:

SELECT
  udfDayOfWeek(p.SignupDate, 3) AS SignupDayOfWeek,
  p.FirstName,
  p.LastName
FROM Profile p;
codemonkey
are you serious?
hobodave
+1 lol... so i got a little bored.
codemonkey
You are crazy codemonkey :D
picca
+3  A: 

Use WEEKDAY() instead, it begins on Monday. If you need to start at index 1, use or WEEKDAY() + 1

nos
Sometimes I'm just dumb. I could figure out, that such function is natively supported by MySQL. Thank you nos.
picca
A: 

try to use WEEKDAY() function