SQL Server query (view) Convert String to DateTime - sql-server

I'm a bit rusty and seem to have completely forgot how to do this. I am receiving data and the datatime column is in string format char(12).
Example : 201411061900
How would I write the query (view) to convert that to DateTime?
I've used CONVERT (datetime, dbo.KWH.mr_dtm,120), but I get the error Conversion failed when converting date and/or time from character string.
I haven't had much luck. Thank you very much in advance.
If you want to suggest -5 time zone also, I wouldn't mind. :)

Magnus answered my question. I wanted to post it here incase it helps anyone in the future.
Here is the link to the answer.
There is no output format identifier (like for example 120) that lets you convert a char(12) into a datetime in SQL Server. But you could use the Substring function:
Select Cast(Substring(dbo.KWH.mr_dtm,1,8) + ' ' + Substring(dbo.KWH.mr_dtm,9,2)+':'+ Substring(dbo.KWH.mr_dtm,11,2) as DateTime)
Thank you to everyone! It is very much appreciated.
Oh, and this post help me solve my timezone setup.
Convert Datetime column from UTC to local time in select statement
Many thanks to Michael Goldshteyn for the timezone convert.

Related

How to get rid of the following error? Converting date from string is failed

In SQL Server, I am getting the error:
Error -2147217913: Conversion failed when converting date an/or time from character string.
Error in converting
I am sure that my fields are in date field, but why this error keeps on showing?
First I validated first if the data type is really a date column:
CASE
WHEN ISDATE(dbo.AdditionalDetailInfo.UserDefined2) = 1
THEN dbo.AdditionalDetailInfo.UserDefined2
ELSE NULL
END AS ReceivedDate
I found out that yes, it's correct. so i proceed with converting this field where UserDefined2 value should always be plus 1 day.
CONVERT(VARCHAR(12), DATEADD(DAY, 1, CONVERT(DATETIME, dbo.AdditionalDetailInfo.UserDefined2)), 103) AS ReceivedDate
Please let me know if there's something wrong with my query as I really can't diagnose what went wrong.
See screenshot:
See this link, the actual data and in SQL server + 1 day
Maybe the field is indeed a date field, so it could be that no conversion is required. Try DATEADD(DAY, 1, dbo.AdditionalDetailInfo.UserDefined2).
If the column is indeed a string column, the you forgot to specify the style parameter when reading the value, you only used it when converting back. Try this instead:
CONVERT(VARCHAR(12), DATEADD(DAY, 1, CONVERT(DATETIME, dbo.AdditionalDetailInfo.UserDefined2, 103)), 103) AS ReceivedDate
MSDN says that date, time and datetime types are not allowed as arguments to ISDATE but in practical terms, passing a date to it:
SELECT ISDATE(getutcdate())
Causes the datetime to be converted to varchar implicitly, passed to ISDATE as varchar, which promptly then returns a 1
As such we've no guarantee that your column really is a date type like you say, so I'm guessing it's probably a string.
Really, what you should do is change your column to be a date type. Don't store dates as strings; if Microsoft had intended you to do this and thought for a second it was a good idea, they wouldn't have implemented other column types than char based ones
If you cannot convert your column to date then you'll need to find the bad value:
select * from table where isdate(column) =0
Note that your attempt to convert style 103 (dd/mm/yyyy) may be failing because you have data that isn't in this style eg Christmas as 12/25/2000
Isdate might not pick this up because your database date format is set to mm/dd/yyyy and isdate thinks it's ok. Change your database date format so that isdate can properly tell what is a good date and what is a bad date
https://learn.microsoft.com/en-us/sql/t-sql/functions/isdate-transact-sql?view=sql-server-2017
And then, please, for the love of doing this properly, use a date typed column, not a string typed one
We need more information. In particular, we need to know what data type the UserDefined2 is. If you tell us that, then we can give better replies.
Just a note that ISDATE is a pretty worthless function since it returns 1 if the string is convertible to datetime. But what if what you really have os datetime2? Or smalldatetime? Because of that, use TRY_CAST instead.
Also, you just gave us pieces of queries, expressions. We don't see the context. There is something called predicate pushing in SQL Server that can mess things up for you (SQL Server pushes a predicate deeper into the query resulting that an expression work over non-datetime values even though you think that you have excluded them in a WHERE clause.
Also, note that how a datetime value is interpreted when you have separators and use the old types (datetime or datetime2) depends on the login's language setting.
More info in http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

SQL Server Convert datetime to mm/dd/yyyy format but still be a datetime datatype

I would like to keep my dates as datetime datatype by also be in MM/DD/YYYY format. I know how to do this by converting them to a varchar, but want to keep the datetime format. Can anyone help with this?
Currently I have tried
SELECT CONVERT(datetime, GETDATE(), 101)
which is not working...
There is a basic misunderstanding in your question. Repeat after me: Datetimes don't have a format.
It helps if you think of them as just an array of seven integers (year, month, day, hours, minutes, seconds, milliseconds) with certain constraints. That's not in any way accurate, but it helps to get the notion out of your head that something akin to 12/31/2015 is stored in your database.
Datetimes only get a format when (implicitly or explicitly) being converted to strings. You already know how to set the format when explicitly converting to string, now all that is left to do is to find the implicit conversion that is obviously bothering you and replace it with an explicit one.
Date and datetime Values stored in the database are NOT in any recognizable format. They are stored in binary (1s and 0s) in a proprietary format where one part represents the number of days since a defined reference date (1 jan 1900) in SQL server). and the other part represents the time portion of the value. (in sql server, its the number of 1/300ths of a second since midnight.)
ALL formatting of dates and date times, no matter what format you wish for, is done only after the values have been extracted from the database, before you see them on screen, in whatever application you are using.
You can find all the formats that the SQL Server convert function can use on this MSDN Convert Link

Date conversion failing on selected date

Hi, I am wondering why this date: 11/4/2011 fails when I do a conversion.
E.g. convert(date,date_field,103) returns as expected but when the convert function is trying to convert this date 11/17/2011 it returns conversion failed.
I tried ltrim to see if there is white space but the same error is returning,
I also tried isdate to make sure it is a date and isdate is returning greater than 0.
I know this is basic but could someone give an insight as to why it is rejecting the date?
Thank you.
MSDN says 103 = dd/mm/yyyy. Your date is "11/17/2011".
Is there a 17th month?
use varchar instead of date. like below
Select Convert(Varchar,'11/17/2011',103)

Date conversion

I have a table with a datetime column I want to retrieve the date in hh:mm:ss where hours is 12hour.
I have tried the following.
convert(varchar(10), t2.CSM_START_TIME,108),
convert(varchar(2),datepart(hour,t2.CSM_START_TIME))
+':'+convert(varchar(2),datepart(mm,t2.CSM_START_TIME))
+':'+convert(varchar(2), datepart(SECOND,t2.CSM_START_TIME))
as START_TIME
SELECT LTRIM(RIGHT(CONVERT(CHAR(20),GETDATE(),22),11));
Result:
11:40:15 PM
Or if you really don't want the AM/PM (which I don't understand):
SELECT LTRIM(LEFT(RIGHT(CONVERT(CHAR(20), GETDATE(),22),11),8));
Result:
11:40:15
Much, much, much better to format this at the client. For example, if you are using C#, look at .Format() and .ToString(). Don't make SQL Server do your dirty presentation work, especially when you have much more flexible features in a more powerful language.
This got me what I wanted.
,substring(convert(varchar(40), t2.CSM_START_TIME,109),12,9)+' '+substring(convert(varchar(40), t2.CSM_START_TIME,109),25,2)
you should try this
DATE_FORMAT(NOW(),'%h:%i %p')
or you will find more here http://www.w3schools.com/sql/func_date_format.asp.

Specific Date Format

Here's a simple one for you guys.
I need to convert the result of GetDate() in this format : YYYY-MM-DD directly in SQLServer2008.
But I can't find exactly the one i'm looking for here.
Thanks in advance.
The trick is to truncate one that starts with the format you want. One way is to cast it as a string type with only the amount of characters you need:
SELECT CONVERT(CHAR(10), GETDATE(), 120);
See below the format being used to convert the date information

Resources