SQL date formats - sql

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.

Related

Parse values of different type to date

I'm trying to parse certain columns into a date format and have had success doing so, but have run into an error due to inconsistency that lies in the data.
My date columns are currently integers in the form of YYYYMMDD, so I've used the following in the select statement to parse into dates:
CONVERT(datetime, CAST(date_column AS CHAR(8)), 112)
This works as expected, transforming my data into a YYYY-MM-DD format.
I run into the following error though:
Conversion failed when converting date and/or time from character
string.
After looking through the data a bit, it turns out I have some cases of inconsistent data values, such as -1 and 10630 instead of the expected YYYYMMDD value.
Do I just need to add a WHERE statement to only apply CONVERT and CAST to YYYYMMDD fields while filtering out fields with bad data? If so, how would I do this, or is there a better way?
Thanks in advance
Let me assume you are using SQL Server, based on the syntax of your SQL. You shouldn't actually need the 112. 'YYYYMMDD' is the default date format for SQL Server.
In any case, you can use TRY_CONVERT():
TRY_CONVERT(datetime, CAST(date_column AS CHAR(8)), 112)
This returns NULL if the value cannot be converted. You can find the offending values using:
select date_column
from t
where try_convert(datetime, cast(date_column as char(8)) is null and
date_column is not null;
Use Parse() or Try_parse()
select parse('22-JAN-1989' as date)
select parse('04-March-1992' as date)
select parse('03/10/2020' as date)
select parse('07-05-1958' as date)
select parse('Aug 25,2016' as date)
Every example above returns a valid date.
You can also add USING 'en-US' or such if you want a different culture.
If you are getting numeric values, and you know the starting date, use
select IsNull(try_parse('16500' as date),dateadd(d,cast('16500' as int),'1/1/1980'))

SQL How to format M/DD/YYYY (1/31/1960) to DD/MM/YYYY (31/01/1969)

I have a column that has date and time mixed together i.e. 1/31/1960 12:00:00AM and I would like to convert them into two-column through SQL function:
(a) DD/MM/YYYY i.e 31/01/1969
(b) HH:MM i.e 12:00
Thanks in advance.
Take a look at the CONVERT() function, specifically the style for datetime. Additionally, we can CAST() the DATETIME as a TIME data type to extract the time.
Assuming your original column is a DATETIME data type, you can run
SELECT
CONVERT(NVARCHAR(24),{DateField},103)
,CAST({DateField} AS TIME)
If it is string, you can cast it then convert
SELECT
CONVERT(NVARCHAR(24),CAST('1960-01-31' AS DATETIME),103) AS ReportingDate
,CAST(CAST('1960-01-31' AS DATETIME) AS TIME) AS ReportingTime
If you're on a sufficiently recent version of SQL Server, the FORMAT() function is your friend.
DECLARE #d DATE = GETDATE();
SELECT FORMAT(#d, 'dd/MM/yyyy');
Note, that second argument is a .NET formatting string, so you should be able to use whatever is available from the Framework.

How do I convert a value after using DATEADD with it

I have a little query that strips the date from the datetime field but when I try to convert it from GMT to CST it readds the date. Is there a better way to do this?
Location table:
arrival
4-6-2018 12:35:43
SELECT arrival
FROM(
SELECT CONVERT(VARCHAR(8), arrival))
FROM locations
)a
This query will give me this result:
12:35:43
SELECT (DATEADD(hour,-5,arrival))
FROM(
SELECT CONVERT(VARCHAR(8), arrival))
FROM locations
)a
4-6-2018 12:35:43
This query will give readd the date. How can I remove the date and then do the dateadd function without it readding the date
arrival seems to be a DateTime, which always carries a date part. You need a time instead, supported by SQL Server 2008+:
cast(DATEADD(hour,-5,arrival) as time)
To quote from DATEADD (Transact-SQL) - Return Types:
The return data type is the data type of the date argument, except for string literals. The return data type for a string literal is datetime. An error will be raised if the string literal seconds scale is more than three positions (.nnn) or contains the time zone offset part.
Emphasis my own.
As you are passing a string (varchar), then DATEADD is returning a datetime.
Like those in the comments have said, if you use the correct data type (time) this problem goes away:
SELECT DATEADD(HOUR, -5,CONVERT(time,Arrival))
FROM (VALUES('4-6-2018 12:35:43'),('4-6-2018 07:35:43'),('4-6-2018 03:35:43')) V(Arrival)
Probably this is what you are asking for:
SELECT Convert(Varchar(8), DATEADD(hour,-5,arrival), 108)
FROM locations;
Note: This is compatible with SQL server versions that doesn't have Time datatype too.

Convert datetime string in datetime format in SQL server

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)

Formatting Dates In SqlServer To Use As Comparison

This should be easy
I have a date column on table A
SELECT * FROM TABLEA
WHERE DTE = '01/02/2010'
The problem is that this is deployed onto US servers and I have no control over the date as its an arg.
How can I tell SqlServer to treat this date as being in that format??
I gave tried this:
SELECT *
FROM TABLEA
WHERE DTE = CONVERT(VARCHAR(10), '01/01/2010' , 101) AS [DD/MM/YYYY]
Your last try was almost correct, but it should have been
SELECT * FROM TABLEA WHERE AS_OF_DATE = CONVERT(DATETIME, '01/01/2010', 101)
Use a safe format. For dates (without a time component), the safe format is YYYYMMDD, e.g. today is '20100209'.
For datetimes, the safe format is YYYY-MM-DD'T'HH:mm:SS, where 'T' is the literal T, so right now is '2010-02-09T11:10:30'.
(When I'm saying safe, I mean that SQL Server always, unambiguously, knows how to convert these strings into datetime values)
Check out this reference article: The ultimate guide to the datetime datatypes
EDIT: Specifically what Tibor says about SET DATEFORMAT & SET LANGUAGE, since you mention that you have no control over the input format.
Another option is a double conversion (check performance when used as criteria):
select strTempNo, dtmTempDateStart,
convert(varchar(10), Convert(datetime, dtmTempDateStart, 103), 126) As UTCDate
I use 103 here as the data is already in UTC format but this works as well (UTC ISO8601 is 126).
If your dates are known to be always in American format you have to use 101.
Alternatively use 112 (ISO "safe" format) and cut the first 8 characters out of the string.
Data sample: (Sorry, don't have an American date table available)
521002 2008-09-1500:00:00.000 2008-09-15
580195 2008-04-1500:00:00.000 2008-04-15
530058 2008-09-2200:00:00.000 2008-09-22
580194 2008-04-0200:00:00.000 2008-04-02
500897 2008-07-0100:00:00.000 2008-07-01
500966 2008-09-2300:00:00.000 2008-09-23