Elegantly convert DateTime type to a string formatted "dd-mmm" - sql

We have the following solution:
select
substring(convert(varchar(20),convert(datetime,getdate())),5,2)
+ ' ' +
left(convert(varchar(20),convert(datetime,getdate())),3)
What is the elegant way of achieving this format?

You can do it this way:
declare #date as date = getdate()
select replace(convert(varchar(6), #date, 6), ' ', '-')
-- returns '11-Apr'
Format 6 is dd mon yy and you take the first 6 characters by converting to varchar(6). You just need to replace space with dash at the end.

You can use the dateName function:
select right(N'0' + dateName(DD, getDate()), 2) + N'-' + dateName(M, getDate())
If you really want the mmm part to only have the tree-letter abbreviation of the month, you're stuck with parsing the appropriate conversion type, for example
select left(convert(nvarchar, getDate(), 7), 3)
The problem is that dateName doesn't have an option to get you the abbreviated month, and the abbreviation isn't always just the first three letters (for example, in czech, two months start with Čer). On the other hand, convert 7 always starts with the abbreviation. Now, even with this, I assume that the abbreviation is always three letters long, so it isn't necessarily 100% reliable (you could search for space instead), but I'm not aware of any better option in MS SQL.

DECLARE #t datetime = getdate()
SELECT CONVERT(VARCHAR(24),LEFT(#t,6),113)

Try this...
SELECT LEFT(CONVERT(NVARCHAR(10), GETDATE(), 6), 6)

Related

I have a column of dates in varchar and i need to convert to date

The dates are currently displayed as: ddmmmyyyy (12DEC2013)
I've been playing around with this formula:
DECLARE #Date char(8)
set #Date='12312009'
SELECT CONVERT(datetime,RIGHT(#Date,4)+LEFT(#Date,2)+SUBSTRING(#Date,3,2))
but I didn't have any success, can someone help me out with this. Additionally all my dates are in a column called TERMDT and I'd like to put all the new date values in a new column formatted as such.
Just give convert() an appropriate 3rd argument (the format):
SELECT CONVERT(datetime,
RIGHT(d, 4) + LEFT(d,2) + SUBSTRING(d, 3, 2),
112)
from (select '12312009' as d) t

Convert date to SQL datetime

I'm somewhat new to T-SQL and despite reading a number of articles that indicate this should work, I'm having trouble converting October 1st of the current year to a datetime.
I've tried:
SELECT CAST(DATEPART(year, GETDATE()) + '1015' AS DATETIME)
SELECT CONVERT(datetime, 'Oct 15 ' + DATEPART(YEAR,GETDATE()),100)
And all kinds of variations.
Any ideas? I need to set a datetime variable to whatever Oct 1st of the current year is.
What you're trying to is close, but DATEPART returns a number, so the "+" is doing addition, not concatenation.
Try it like this:
SELECT CAST(CAST(DATEPART(year, GETDATE()) AS VARCHAR(4)) + '1015' AS DATETIME)
edit -- Ed beat me to it, and the Concat function is better too.
But if you really wanted to knock it out of the park, try this...
SELECT DATEADD(month, 9, DATEADD(year, DATEDIFF(year, 0, getdate()), 0)) As October1CurrentYear
No casting required!
Your first query is very close. The problem is that the plus sign (+) for concatenation is actually giving you a numeric value, which you can't cast to a date.
To concatenate a year and '1015' and end up with a string, use the CONCAT function instead:
SELECT CAST(CONCAT(DATEPART(YEAR, GETDATE()), '1015') AS DATE)

SQL: How to find records between 2 dates

The dates are in Y2K date string format
eg) 1120104 = 20120104
Running SQL Server 2008
Well I agree with #usr, first, stop storing dates this way.
If you can't, then add a computed column (which you could even persist and/or index):
ALTER TABLE dbo.MyTable ADD RealDate
AS CONVERT(DATE, RIGHT(col, 6), 12);
If you can't do that, then create a view:
CREATE VIEW dbo.SmarterView
AS
SELECT /* other columns, */
RealDate = CONVERT(DATE, RIGHT(col, 6), 12)
FROM dbo.MyTable;
Then:
SELECT ... FROM dbo.MyTable -- or dbo.SmarterView
WHERE RealDate >= #Start
AND RealDate < DATEADD(DAY, 1, #End);
Open-ended ranges are far better than BETWEEN - calculating the end of the month sucks, especially in February, and especially if you have any potential for date/time data type changes. See:
What do BETWEEN and the devil have in common?
If you have dates in the 1900s, then it is slightly more involved:
CONVERT(DATE, CONVERT(CHAR(2), 19 + CONVERT(INT, LEFT(col, 1))) + RIGHT(col, 6), 112);
In any case, it's irrelevant, since the OP stated they will store it correctly as DATE.
First advice: store the dates as data type date or datetime so that you can actually search on them.
If you don't want that, you need to convert the strings to date first so that you can search on them:
where convert(date, my_nasty_string_column_with_dates) between #a and #b
This is a perf problem because the query will never be able to seek on an index.
You should be able to compare at Y2K date with another with simple equality checks. If you want to convert the Y2K to DateTime then you need to add 19000000 then convert it like this example:
DECLARE #Y2KDate INT
SET #Y2KDate = 1120104
DECLARE #DateTime DateTime
SET #DateTime = CONVERT(DATETIME, CONVERT(CHAR(8), #Y2KDate + 19000000), 112)
PRINT #DateTime
Prints the following output
1120104
20120104
Jan 4 2012 12:00AM

Add characters in the variable

I need to make the string/varchar variable with value 20061212 to be string/varchar value 2006-12-12 00:00:00
I can't find the right SQL syntax code to make it happened in SQL Server.
The code can be created as stored procedure or similar in SQL Server.
SELECT
LEFT(#string, 4)
+ '-' + SUBSTRING(#string, 5, 2)
+ '-' + SUBSTRING(#string, 7, 2)
+ ' 00:00:00'
You could cast your string to a DATETIME and then convert it back to a string in your chosen format. But that would likely be slower than this more explicit option.
SELECT
CONVERT(VARCHAR(19), CAST(#string AS DATETIME), 120)
You can use stuff
declare #s varchar(8) = '20061212'
select stuff(stuff(#s, 7, 0, '-'), 5, 0, '-')+' 00:00:00'
You can use the SUBSTRING() function (detailed here: http://www.sql-statements.com/sql-substring.html) to take apart the original string, and then put the pieces back together with the added dashes & time at the end using the concatenation operator +.
Culture independent variant:
SELECT CONVERT(varchar, convert(datetime, '20061212', 112), 120)
BUT this only valid for DATETIME-allowed range of dates, use DATETIME2 instead

SQL Converting string MMM.YY to date

how do i convert/cast a column contains strings e.g. Jan.08,Feb.08.. into date format so that i can sort them?
Greatest Thanks!
I'd just format as a convertible string for the first of the relevant month, and then cast to datetime, e.g.
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...is an expression that will yield a datetime that should be sortable, so:
SELECT
YourMonthAndYearColumnName
FROM
YourTable
ORDER BY
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...should do what you're looking for.
If you can make the assumption that all dates will be within the last ten years, you can use the following code:
select convert(datetime, replace('Jan.08', '.', ' 20'))
select convert(datetime, replace('Dec.08', '.', ' 20'))
That formats the string into the format "Jan 2008", which is unambiguous. "Dec.08" could be "8th December this year" or "The month of december 2008".
Or you could use Matt Gibson's suggestion of prepending a "1." to your date before conversion. That removes the ambiguity, and has the advantage of using whatever defaults that SQL server has for dates (i.e. 50 is 1950 and 49 is 2049).
select convert(datetime, '1.' + 'Jan.08')
select convert(datetime, '1.' + 'Dec.49')
select convert(datetime, '1.' + 'Jan.50')