先获得;年度最后一天和;月变量

时间:2014-03-21 19:48:59

标签: mysql date variables time

使用MySql

我有以下变量(以“3”和“2014”为例):

SET @Month = 3;
SET @Year = 2014;

期望的结果

I'd like to get the first day of the month and the last day of the month separately, 
using the variables (avoiding any NOW() or CURDATE() formulas), in %Y-%m-%d format. In other words:

2014-03-01
2014-03-31

我尝试了以下基本功能的许多可能性,加上一些我已删除

SELECT LAST_DAY(`SELECT(@Year)-03-01`)
SELECT LAST_DAY('@Year-@Month')
SELECT DATE_FORMAT(?, '%Y-%m-01')

2 个答案:

答案 0 :(得分:8)

SET @Months = 3;
SET @Years = 2014;
SELECT DATE_FORMAT(DATE(concat(@Years, '-', @Months, '-01')), '%Y-%m-%d');
SELECT LAST_DAY(DATE(concat(@Years, '-', @Months, '-01')));

'年份'和'月'是MySQL中保留的函数名称。所以我建议重命名它以避免混淆。

答案 1 :(得分:0)

SELECT DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)), 
                INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL 1 MONTH)))-1 DAY) AS firstOfNextMonth,
       LAST_DAY(DATE_ADD(NOW(), 
                INTERVAL 1 MONTH)) AS lastOfNextMonth

来源:Get the first and last date of next month in MySQL