Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL- How to convert a YYYYMM number to a date

Tags:

sql

So I'm pretty new to SQL and I have a column full of numbers that list year and month in YYYYMM format (i.e. 201607 for July 2016). What I'd like to know is if I can convert this into proper date format within SQL. I've done a fair bit of research and I've seen a lot of answers regarding converting YYYYYMMDD form to a date, but not much with only the 6 characters I've got.

Anybody got any ideas?

like image 758
David Lawrence Avatar asked Jul 05 '18 09:07

David Lawrence


2 Answers

Assuming that every one would be the first of the month (i.e. 201807 would be 2018-07-01):

CONVERT(date, YourColumn + '01')

If you require a different day in that month, you'll need to provide more detail.

like image 56
Larnu Avatar answered Nov 03 '22 08:11

Larnu


You can do like this if you want:

   select *, FORMAT(DATEFROMPARTS(1900, right(YearMonthKey,2), 1), 'MMMM', 'en-US') +' '+ Left(YearMonthKey,4)  as MonthYearName from (
select 201709 as YearMonthKey
)x

Result

enter image description here

like image 2
SqlKindaGuy Avatar answered Nov 03 '22 09:11

SqlKindaGuy