1

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')
Ken
  • 1,001
  • 3
  • 14
  • 27

2 Answers2

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')));

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

Slowcoder
  • 2,060
  • 3
  • 16
  • 21
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

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

Community
  • 1
  • 1
suuuzi
  • 602
  • 1
  • 8
  • 19