Convert datetime string in datetime format in SQL server - sql

I'm using MS SQL server and I have a date field of type text. The dates stored there are in this format
2017-03-01T18:23:02+0700
I'm trying to convert this field in a datetime field but I fail. I have tried
CONVERT(datetimeoffset,date, 127)
CONVERT(datetime,date, 127)
CONVERT(datetime2,date, 127)
but I keep getting
Conversion failed when converting date and/or time from character
string.
I think the problem is that according to ISO8601 the time offset must be in the format hh:mm while mine is hhmm. I don't mind keeping only the date (yyyy-mm-dd) if it is more easy.
I have read similar question but none matches exactly my case and I can't figure out the solution.

Try this
Declare #dt varchar(50)
set #dt = '2017-03-01T18:23:02+0700'
select convert(datetime, replace(LEFT(#dt, LEN(#dt) - 1), '+', '.'), 126)

If you need only date part then you can use below query
SELECT CAST(LEFT('2017-03-01T18:23:02+0700',10) as DATE)

Use Below query to convert datetime :
SELECT CONVERT(DATETIME,REPLACE(REPLACE('2017-03-01T18:23:02+070','T','
'),'+','.'),103)
For DATE only use below query :
SELECT CONVERT(DATE,REPLACE(REPLACE('2017-03-01T18:23:02+010','T','
'),'+','.'),102)

It doesn't seem to work in both ways (both raise error):
SELECT CONVERT(datetime,'2017-03-01T18:23:02+0700',127)
SELECT CONVERT(datetime,'2017-03-01T18:23:02+07:00',127)
It seems that it works only specifying Z as time zone:
SELECT CONVERT(datetime,'2017-03-01T18:23:02Z',127)

Related

How to get datepart from datetime in a Column

I want to convert the column (EXECUTION_LOCAL_DATE_TIME) which has datetime format as (YYYY-MM-DD hh:mm:ss.nnnnnnn) to format (YYYY-MM-DD). Ho do i get this. I am working on SQL server management studio
If your intention is to just get the DATE part of a DATETIME then you can just convert the format to DATE (note that this will return a 'Date' datatype, not specifically formatted to a string 'YYYY-MM-DD'.)
eg:
DECLARE #Dt DATETIME = '2019-01-25T12:00:00'
SELECT CONVERT(DATE, #Dt)
Will return '2019-01-25'
You want the CAST() function:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017
Ideally you should return the datetime format from your query and let your presentation layer handle formatting.
However if you are using SQL server 2012 or higher then you can use the Format() function. See the below answer:
Convert Date format into DD/MMM/YYYY format in SQL Server
If you're using SQL Server 2012 or higher you can use the FORMAT() function.
In your case you'd need
SELECT FORMAT(EXECUTION_LOCAL_DATE_TIME, 'yyyy-MM-dd') FROM TABLE_NAME
You can find additional info here
https://www.mssqltips.com/sqlservertip/2655/format-sql-server-dates-with-format-function/
https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql?view=sql-server-2017
Here Is the Code Worked For me
SELECT convert(varchar, EXECUTION_LOCAL_DATE_TIME, 111) from Tablename
The Execution_Local_Date_Time will be Converted to yyyy/mm/dd format.

CASTing and converting functions in SQL Server

I am trying to convert dd.mm.yyyy to yyyy-mm-dd.
select convert(date,CAST(WEEK_DATE as nvarchar(220)), 120)
from z_fact
Error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
How can I resolve this?
Since your date is actually text, you must first convert it to a bona fide date using CONVERT. Then, use CONVERT on that date a second time to generate the text output you want.
SELECT CONVERT(varchar(20), CONVERT(datetime, '15.03.18', 4), 120);
Demo
Note that it is generally bad practice to store your dates as text. Hopefully you can use my answer to tidy up your table. For example, you could add a new datetime column new_dt and then update it using:
UPDATE yourTable
SET new_dt = CONVERT(datetime, old_dt, 4);
Don't worry about the internal format used by SQL Server. If you still need to display yyyy-mm-dd output, then use CONVERT again, as I did in my first query.
You can try this:
declare #dt NVARCHAR(12) = '15.03.18'
SELECT CONVERT(DATE,#dt,3)
GO

SQL date formats

How can I convert this 201402110544 to date(2014-02-11) in SQL server 2008?
You can cast as DATE data type (https://msdn.microsoft.com/en-us/library/bb630352(v=sql.100).aspx)
SELECT CAST(datetime_value AS DATE)
SELECT CAST(GETDATE() AS DATE) --> 2015-08-18
If you have a string to cast as DATE you can use:
SELECT CAST(LEFT('201402110544', 8) AS DATE)
You trim out the time part, by taking 1st 8 chars (YYYYMMDD) and will result a valid string to cast as DATE.
If this format is always the same, you can do this
DECLARE #d VARCHAR(20)='201402110544'
SELECT CAST(SUBSTRING(#d,0,9) as DATETIME)
Also have a look at The ultimate guide to the datetime datatypes which explains in detail about handling date-times
String to date conversion sure is a weakness of SQL Server. CONVERT does that, but can only deal with a number of given formats. So you must convert your string into such a format first and then convert it to date afterwards.
One such format is 120 = 'yyyy-mm-dd hh:mi:ss' which I think comes closest to yours. Another 102 = 'yyyy.mm.dd' suffices to get the date.
convert(
date,
concat(substring(datestring, 1,4), '.',
substring(datestring, 5,2), '.',
substring(datestring, 7,2)),
102)
from data;
SQL fiddle: http://www.sqlfiddle.com/#!3/9eecb7/3689
EDIT: I stand corrected. Horia is right; CAST supports 'yyyymmdd', so you can use it directly by merely cutting of the string's time part. This is more readable than my suggestion above, which makes CAST the better option in your case.

SQL - Convert String to Date and compare - Conversion failed when converting datetime from character string

I currently have dates stored in a general attribute field in the database as a string.
They are all stored in the format DD/MM/YYYY for example 01/01/2000
I am able to convert them them to datetime successfully by using the following in my select statement. For example CONVERT(DATETIME, attribute.field_value, 103) where attribute.field_value contains a date.
The SELECT statement works fine and returns the whole table with them correctly.
I can also return a column with todays date in the same format as follows CAST(getdate() AS datetime)
The problem occurs when I try to compare, now I only want to return everything that is newer than today in pseudo code that would dateNewerThanToday > dateToday
Therefore I have tried
WHERE CONVERT(DATETIME, attribute.field_value, 103) > CAST(getdate() AS datetime)
this gives me the error
Conversion failed when converting datetime from character string.
I have tried a multitude of cast/converts to get it to work. I have also wrapped by select so I am only doing it on dataset with the correct data.
Any help would be super useful! Many thanks in advance!!
A couple of things ..
You do not need to convert to GETDATE() to DATETIME data type as it already returns datetime data type.
Instead of CONVERT(DATETIME, attribute.field_value, 103)
use
CONVERT(DATETIME, attribute.field_value) or CAST(attribute.field_value AS DATETIME)
Add a where clause in your select to get only valid DATETIME values. something like
WHERE ISDATE(attribute.field_value) = 1
This will filter out any values which appears to be a date value but sql server doesnt see them as valid date values.
Important Not
Use appropriate data types. If this column is storing date values why not use the DATE or DATETIME data types.
I ran into this exact problem.
Values from a VARCHAR(50) column returned in the SELECT could be cast as date without issue. However when cast in a comparison in the WHERE clause the error occurred.
Of note, the error only occurred when I had other restrictions in the WHERE clause.
When I added ISDATE() to the WHERE clause, the error no longer occurred.
e.g. Shortened example of what worked:
SELECT CONVERT(DATE, mat.myAttributeColumn), mdct.myDateComparisonColumn
FROM myAttributeTable mat
JOIN myDateComparisonTable mdct ON mdct.key = mat.key
WHERE ISDATE(mat.myAttributeColumn) = 1
and mdct.myDateComparisonColumn < convert(DATE, mat.myAttributeColumn)

datetime conversion issue in sql server

if i try to cast string date to datetime like
select cast('12/01/2010' as datetime) then
it works
but if i try to cast like
select cast('22/01/2010' as datetime) then it is giving error.
again if i try to cast string date to datetime like
select cast('2010/12/01' as datetime) then it works
but if i try to cast like
select cast('2010/25/01' as datetime) then it is giving error. my requirement is whatever way user input date that should be successfully converted to datetime. please tell me best solution
In your case the sql server assumes, that date format id mm/dd/yyyy - US format,
you want to use French format, so use convert
select CONVERT(DATETIME, '12/01/2010', 103)
instead you'll get an error because there in no such a month number - 22
The best solution when passing datetime as string - to use short(without timezone) ISO format:
yyyyMMdd HH:mm:ss.ffff
I recommend you to use fixed '20111231' format. You do not need to use cast, convert or similar command.