简体   繁体   中英

Get First & Last Day of Month from Year & Month variables

Using MySql

I have the following variables (filled in with "3" and "2014" as an example):

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

Desired Results

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

I've tried many possibilities of the following base functions, plus some I've deleted

SELECT LAST_DAY(`SELECT(@Year)-03-01`)
SELECT LAST_DAY('@Year-@Month')
SELECT DATE_FORMAT(?, '%Y-%m-01')
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')));

'Year' and 'Month' are reserved function names in MySQL. So I would suggest renaming it to avoid the confusion.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM