答案 0 :(得分:48)
这是根据当前日期获取一周的第一天和一周的最后一天的准确方法:
adddate(curdate(), INTERVAL 1-DAYOFWEEK(curdate()) DAY) WeekStart,
adddate(curdate(), INTERVAL 7-DAYOFWEEK(curdate()) DAY) WeekEnd
答案 1 :(得分:43)
答案 2 :(得分:4)
到目前为止,在这个主板上最受欢迎的答案看起来像是基本形式:
SELECT STR_TO_DATE('201003 Monday', '%X%V %W');
这是一个很好的答案,但是在你开始将它与week()函数结合使用的某些日子它会崩溃,除非你添加一些额外的逻辑。
这是同一件事的漫长,凌乱的版本,但它似乎在所有日子都有效(BTW当前日期已内置于此asnwer):
SELECT STR_TO_DATE(
(IF( CAST(WEEK(NOW(),0) AS UNSIGNED) = 0,
(CONCAT(
CAST((CAST(YEAR(NOW()) AS UNSIGNED) - 1) AS CHAR),
'52 Sunday')),
(CONCAT(
CAST(YEAR(NOW()) AS CHAR),
IF( CAST(WEEK(NOW(),0) AS UNSIGNED) < 10,'0','' ),
CAST(WEEK(NOW(),0) AS CHAR),
' Sunday')))),
'%X%V %W');
这个混乱处理当一年中某些日子年度结束时出现的问题。例如,2011年是在星期六开始的,因此本周开始的星期日是去年。这是带有硬编码示例的选择:
SELECT STR_TO_DATE(
(IF( CAST(WEEK('2011-01-01',0) AS UNSIGNED) = 0,
(CONCAT(
CAST((CAST(YEAR('2011-01-01') AS UNSIGNED) - 1) AS CHAR),
'52 Sunday')),
(CONCAT(
CAST(YEAR('2011-01-01') AS CHAR),
IF( CAST(WEEK('2011-01-01',0) AS UNSIGNED) < 10,'0','' ),
CAST(WEEK('2011-01-01',0) AS CHAR),
' Sunday')))),
'%X%V %W');
YEILDS&gt;&gt; '2010-12-26'
SELECT STR_TO_DATE(
(IF( CAST(WEEK('2011-01-02',0) AS UNSIGNED) = 0,
(CONCAT(
CAST((CAST(YEAR('2011-01-02') AS UNSIGNED) - 1) AS CHAR),
'52 Sunday')),
(CONCAT(
CAST(YEAR('2011-01-02') AS CHAR),
IF( CAST(WEEK('2011-01-02',0) AS UNSIGNED) < 10,'0','' ),
CAST(WEEK('2011-01-02',0) AS CHAR),
' Sunday')))),
'%X%V %W');
YEILDS&gt;&gt; '2011-01-02'
所有这一切,我喜欢发布的其他内容,看起来像这样
SELECT
adddate(curdate(), INTERVAL 1-DAYOFWEEK(curdate()) DAY) WeekStart,
adddate(curdate(), INTERVAL 7-DAYOFWEEK(curdate()) DAY) WeekEnd;
这种方法似乎在没有乱七八糟的所有日期也能正常工作!
答案 3 :(得分:3)
这可能是最简单,最动态的方式。使用以下代码。
SELECT STR_TO_DATE( concat( concat( date_format( CURDATE( ) , '%Y' ) , WEEKOFYEAR( CURDATE( ) ) ) , ' Monday' ) , '%X%V %W' );
答案 4 :(得分:2)
如果您的周开始是星期日,而周末是星期六,请使用以下一个:
SELECT
DATE_ADD(CURDATE(), INTERVAL (MOD(DAYOFWEEK(CURDATE())-1, 7)*-1) DAY) AS week_start,
DATE_ADD(CURDATE(), INTERVAL ((MOD(DAYOFWEEK(CURDATE())-1, 7)*-1)+6) DAY) AS week_end
在MySQL上测试。
答案 5 :(得分:0)
答案 6 :(得分:0)
SELECT CONCAT(RIGHT(STR_TO_DATE(CONCAT(YEARWEEK(NOW()),'Monday'), '%X%V %W'),2),'-',
MID(STR_TO_DATE(CONCAT(YEARWEEK(NOW()),'Monday'), '%X%V %W'),6,2),'-',
LEFT(STR_TO_DATE(CONCAT(YEARWEEK(NOW()),'Monday'), '%X%V %W'),4)) AS 'Lundi',
CONCAT(RIGHT(STR_TO_DATE(CONCAT(YEAR(NOW()), week(now(),3),'Sunday'), '%X%V %W'),2),'-',
MID(STR_TO_DATE(CONCAT(YEAR(NOW()), week(now(),3),'Sunday'), '%X%V %W'),6,2),'-',
LEFT(STR_TO_DATE(CONCAT(YEAR(NOW()), week(now(),3),'Sunday'), '%X%V %W'),4)) AS 'Dimanche';
答案 7 :(得分:0)
除了dcp的回答:
SELECT STR_TO_DATE('201553 Monday', '%x%v %W')
当你星期一的开始是星期一时,会给你星期一。格式说明符只需要写得很小。不需要数学。
答案 8 :(得分:0)
使用上述解决方案进行了测试。我最终用到了:
STR_TO_DATE( concat( YEARWEEK("2012-12-31", 3) , ' Monday' ) , '%x%v %W' )
一些要点:
经过以下日期测试,以查找第一个星期一: