I have a dataset with dates in the format as follows:
10/18/2007 8:00 A.M.
10/20/2007 10:00 A.M.
etc..
I'm having a lot of trouble finding a consistent query to convert a set of varchars in this format to datetime for insertion into a datetime column. I have tried many of the CONVERT styles (found here https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql) but none really works.
In Sql Server 2012 and up: each of these will return null when the conversion fails instead of an error.
try_convert(datatype,val)
try_cast(val as datatype)
try_parse(val as datatype [using culture])
declare #str varchar(32) = '10/20/2007 10:00 A.M.'
select try_parse(replace(#str,'.M.','M') as datetime using 'EN-us')
returns: 2007-10-20 10:00:00
rextester demo: http://rextester.com/KWCF9843
You just need to strip the periods out and then simply convert
Select try_convert(datetime,replace('10/18/2007 8:00 A.M.','.',''))
Returns
2007-10-18 08:00:00.000
Related
I have a column that holds a string time (i.e. 8:00 AM) and I need to convert that to an actual Time and be able to append it onto a DateTime field (which is in DateTime format, not string).
Example:
Date field = 2019-06-25 00:00:00.000
Time field = 8:00 AM
Desired result: 2019-06-25 08:00:00.000
Does anyone know how I can accomplish this in SQL?
I know some people still suggest doing it in code, but I'm writing a query that does a comparison between two DateTime fields (one of which has the integrated DateTime with the proper time and the other in which the date and time are separate)
Using DATETIME + CAST(timevariable AS DATETIME) will return your expected result:
DECLARE #Time AS VARCHAR (10) = '8:00 AM'
DECLARE #DateField AS DATETIME = '2019-06-25 00:00:00.000';
SELECT #DateField + CAST(#time AS DATETIME)
Demo on db<>fiddle
It is also work with 1:00 PM
I am currently working with dates in SQL Server whose datatype is NVARCHAR(max) and whose format is dd-mm-yy hh:mm:ss +tz, meaning they look like this:
31-10-18 18:34:05 +00:00
And, despite all my efforts, I couldn't find a way to convert those dates to datetimes whereas I used all sorts of combinations with the CAST and CONVERT functions.
Most of the time, I had the following error message:
Conversion failed when converting date and/or time from character
string.
And I'm pretty sure it comes from the fact that the year is written as '18' instead of '2018'.
I would therefore like to find the simplest way to perform such a conversion.
You need to set date format before
SET DATEFORMAT dmy;
SELECT CAST('31-10-18 18:34:05 +00:00' as datetimeoffset)
Result
----------------------------------
2018-10-31 18:34:05.0000000 +00:00
I have to save this yyyy-MM-dd HH:mm:ss.ffffff datetime format in MS SQL DB as datetime
so what should be the datatype for it ?
you can use datetime data type as you need 6digit then use
datetime2
datetime2 time range 00:00:00 through 23:59:59.9999999
SELECT convert(DATETIME2, getdate())
its output
2018-07-25 03:28:37.7300000
you can use datetime2(6) according to Dan Guzman comments
The default datetime2 precision is datetime2(7)
I have a column with datetime as the data type
I need to check if that datetime column is between 2:30pm to 3pm, "ignoring" the date
I saw an example in sql server that cast the datetime to float but that did not work in sybase...
does anyone have any idea
thanks
Floor your datetime to midnight of that date, Then use datediff() to get the elapsed time between the two.
DECLARE #dt DATETIME
SET #dt='10/06/2011 2:37:17.390PM'
SELECT
CASE
WHEN DATEDIFF(ms,CONVERT(DATETIME,CONVERT(DATE,#dt)),#dt) BETWEEN 52200000 AND 54000000
THEN 1
ELSE 0
END
I'm converting varchar to datetime in Sql Server 2005. Can I force Sql Server to fail if provided varchar has unexpected format?
Example:
select convert(datetime, '01-2010-02', 103)
Expected result: query fails because 103 means dd/mm/yyyy (see msdn).
Actual result: 2010-02-01 00:00:00.000
Main purpose of requested enforcement is order of day and month. If varchar is provided in format yyyy-mm-dd then Sql Server will treat mm as day and dd as month because of day/month order in provided format (dd/mm/yyyy).
Note: I can write custom function to manually handle this case. But I hope such enterprise DB already can work strictly with data.
I am afraid you have to use CLR Function and take advantage of using DateTime.TryParseExact method. Not an elegant solution but could work.
You can compare the date with a convert to datetime and back again. I don't know for sure if there are any pitfalls doing like this but my limited tests has not discovered any.
if #StrDate = convert(varchar(10), convert(datetime, #StrDate, 103) ,103)
Whenever SQL Server sees a clear candidate for Year, it will always be used as Year.
The remaining DM parts are determined from the order within the DMY setting or the convert format. If that weren't true, then very simple conversions will fall apart.
Example
set dateformat dmy
select 1 a,CONVERT(datetime, '1-2-3') b
union all
select 2,CONVERT(datetime, '2001-2-3')
union all
select 3,CONVERT(datetime, '2001-3-2')
Output
a b
----------- -----------------------
1 2003-02-01 00:00:00.000
2 2001-03-02 00:00:00.000
3 2001-02-03 00:00:00.000
The 2nd and 3rd explicitly put the Year in front, and that is ok
EDIT
Books Online has this to say http://msdn.microsoft.com/en-us/library/ms180878.aspx#StringLiteralDateandTimeFormats
There are quite a few exceptions to SET DATEFORMAT, which plays a role regardless of the 3rd param to CONVERT.
The SET DATEFORMAT session setting does not apply to all-numeric date entries
This [ISO 8601] format is not affected by the SET DATEFORMAT, SET LANGUAGE, of login default language settings.
The SET DATEFORMAT session setting is not applied when you specify the month in alphabetical form.
etc
To specifically validate dd/mm/yyyy, use the below instead
set dateformat dmy
declare #input varchar(10) set #input = '12-2010-01'
-- convert allows the date through
select convert(datetime, #input, 103) -- 2010-01-12 00:00:00.000
-- the case below returns 0 { = invalid date }
-- this uses 8-digit format which is always interpreted YYYYMMDD regardless
-- of language or dateformat settings
select case
when #input not like '__/__/____' then 0
else isdate(right(#input,4)+right(left(#input,5),2)+left(#input,2))
end