How to get end of month date from a "YearMonth" varchar column?

380 Views Asked by At

We have YearMonth VARCHAR(10) column and I am trying to create a date column which will give me last date of the month based on the YearMonth column.

For Example:
201612 - 12/31/2016
201602 - 02/29/2016
201702 - 02/28/2017
2

There are 2 best solutions below

1
On

Assume your varchar is 201612

Select EOMonth(cast(YourVarchar+'01' as date))

Returns

2016-12-31

If you wanted the MM/DD/YYYY format

Select Convert(varchar(10),EOMonth(cast(YourVarchar+'01' as date)),101)
0
On

If you are using a version of SQL before 2012:

Add a month to the date with DATEADD, then subtract a day also with DATEADD

SELECT DATEADD(DAY, -1, DATEADD(MONTH, 1, CONVERT(DATETIME, '201612' + '01')))