T-SQL String to DateTime-conversion - sql

I need to cast string values of the following formats to DateTime:
2042-04
2011-01
Is there an easy way to do this? I've tried CAST AND CONVERT without much luck.
Thanks!

try appending "-01" to the end of it and then doing the cast or convert

declare #S varchar(7)
set #S = '2042-04'
select cast(stuff(#S, 5, 1, '')+'01' as datetime)
YYYYMMDD is a safe format regardless of SET DATEFORMAT. YYYY-MM-DD is not. http://www.sommarskog.se/wishlist.html#YYYYMMDD

SELECT CAST('2011-01-01' AS DATETIME)
SELECT CONVERT(DATE , '2011-01-01')
It seems you need to add a 'day' to the string.

Declare #Table Table
(
ColDateTime Varchar(100)
)
Insert into #Table
Select '2042-04' UNION ALL
Select '2011-01'
Select ColDateTime As VarcharCol,
Cast(
substring(ColDateTime,0,charindex('-',ColDateTime))+substring(ColDateTime,charindex('-',ColDateTime)+1,len(ColDateTime))+'01'
As DateTime) As DateTimeCol
from #Table

Related

How to change a date to a different format

This is a simple question.
How do I transform a date column that comes over as an int.
for example 20190327 convert over to 'MM/dd/yyyy'?
I tried
select *,format(Columnname, 'MM/dd/yyyy') from Table
but this didn't work.
Thank you!
You can try this:
declare #i int
select #i = 20190327
select CONVERT (datetime,convert(char(8),#i))
The following will give you in MM/dd/yyyy format.
SELECT *, CONVERT(nvarchar(30), cast(cast(Columnname as char(8)) as date), 101) as convertedToDate
FROM Table

sql server convert datetime failed

I want to convert this time_stamp column (nvarchar50) into datetime column in SQL server. the value of time_stamp is "2018-02-16 13:30:27+09:00".
I don't know which datetime code should I use to convert it. Can you help?
This is what I tried:
select convert(datetime,time_stamp, 110) from table;
select convert(datetime,time_stamp, 120) from table;
It is failing because of the timezone embedded in the string. However, it will work if you remove the timezone using string function such as LEFT.
SELECT CONVERT(DATETIME, LEFT(time_stamp, 19), 110)
FROM tableName
Here's a Demo.
There is timezone offset in your sample date. If we want to ignore timezone offset then we can use below code -
declare #x nvarchar(50) = '2018-02-16 13:30:27+09:00'
select convert(datetime,convert(datetimeoffset, #x))
Declare #dt NVARCHAR(100) = '2018-02-16 13:30:27+09:00'
select CAST(SWITCHOFFSET(TODATETIMEOFFSET( LEFT(#dt , 19) ,RIGHT(#dt, 6)),0) AS DATETIME)
Returns:
2018-02-16 04:30:27.000

convert string to both date and time

I have a data where date and time comes up in yyyymmdd_time (20161012_1528) format.
I want to convert it to date time in SQL Server DB as 2016-10-12 15:28:00:00
is there any straight forward way to do this.or have to create a custom function?
Declare #String varchar(25) = '20161012_1528'
Select cast(left(#String,8)+' '+Stuff(right(#String,4),3,0,':') as datetime)
Or
Select cast(Stuff(Replace(#String,'_',' '),12,0,':') as datetime)
Returns
2016-10-12 15:28:00.000
Please try following method,
It requires a few datetime and convertion functions to be used
declare #dt datetime
declare #str varchar(40) = '20161012_1528'
select #dt =
DATEADD(MI, CAST(right(#str,2) as int),
DATEADD(hh, cast(SUBSTRING(#str,10,2) as int),
CONVERT(datetime, left(#str,8))
)
)
select #dt
The closest I could find was datetime format 112 which does not account for the "_hhmm". I would highly recommend just placing the convert into your T-SQL as the optimizer does not handle UDFs very well.
The T-SQL looks like:
DECLARE #datetimestring nvarchar(max) = '20161012_1528'
SELECT
dateadd(
minute,convert(
int,substring(
#datetimestring,charindex(
'_',#datetimestring
)+3,2
)
),dateadd(
hour,convert(
int,substring(
#datetimestring,charindex(
'_',#datetimestring
)+1,2
)
),convert(
datetime, substring(
#datetimestring,0,charindex(
'_',#datetimestring
)
), 112
)
)
)
The other option is to format the string to the expected date format which is shorter.
SELECT
convert(
datetime,replace(
stuff(
stuff(
stuff(
#datetimestring,5,0,'-'
),8,0,'-'
),14,0,':'
),'_',' '
)
)

Splitting a datetime and replace the year part

I need to split a date like '01/12/15' and replace the year part from 15 to 2015 (ie; 01-12-2015). I get the year by the sql query:
select YEAR('10/12/15')
It returns the year 2015. but I have to replace 15 to 2015. how do i achieve this.
Anyone here please help me. thanks in advance..
Edited:
I've tried following query too..
declare #date varchar='10/12/2015'
declare #datenew date
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
print #datenew
but it throws some error like this :
Conversion failed when converting date and/or time from character string.
How do I change the varchar to date and replace its year part to 4 digit.. please help me..
DECLARE #intFlag INT,#date varchar(150),#payperiod numeric(18,0),#emp_Id varchar(50)
SET #intFlag = 1
declare #count as int set #count=(select count(*) from #myTable)
WHILE (#intFlag <=#count)
BEGIN
select #emp_Id=Employee_Id from #myTable where rownum=#intFlag
select #date=attendance_date from #myTable where rownum=#intFlag
declare #datenew datetime
SELECT #datenew=convert(datetime,CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103) ,103)
It throws the error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
As you said your column is in varchar type, try the following
Query
CREATE TABLE #temp
(
dt VARCHAR(50)
);
INSERT INTO #temp VALUES
('01/12/15'),
('02/12/15'),
('03/12/15'),
('04/12/15'),
('05/12/15');
UPDATE #temp
SET dt = REPLACE(LEFT(dt, LEN(dt) - 2)
+ CAST(YEAR(CAST(dt AS DATE)) AS VARCHAR(4)), '/', '-');
SELECT * FROM #temp;
EDIT
While declaring the variable #date you have not specified the length.
Check the below sql query.
declare #date varchar(10)='10/12/2015'
declare #datenew date
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
print #datenew
The simplest way by casting Date object to VARCHAR
SELECT RIGHT(CAST(YEAR('10/12/15') AS VARCHAR), 2)
If you want to change the format and get the varchar try to use:
SELECT CONVERT(varchar(10), CAST('10/12/15' AS DATETIME), 105)
I hope it helps.
What datatype is the value '01/12/15'?
Maybe this will help you:
SELECT YEAR(CAST('10/12/15' AS DATE))
Problem with your query is that you haven't specified length for varchar datatype:
declare #date varchar(12)='10/12/2015'
declare #datenew date
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
print #datenew
Try using:
Declare #date nvarchar(20)='10/12/15'
Declare #datenew nvarchar(40)
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
Print #datenew

SQL Server - Converting date in "20140410" format to 04/10/2014 format

I have a table in a server that outputs the date in the following format YEARMONTHDAY
Example 20140410.
Question is how to I convert it to be as MONTH/DAY/YEAR, example 04/10/2014
Thanks!
David
Try this:
declare #theDate varchar(8)
set #theDate = '20140410'
select convert(varchar(10),cast(#theDate as date),101)
I think you can use:
SELECT convert(varchar, getdate(), 101);
Here is one way to do it:
declare #dt CHAR(8) = '20140131'
select #dt, CONVERT(DATE,#dt) as newDt
Here is a link on the CONVERT function http://msdn.microsoft.com/en-us/library/ms187928.aspx and one on date types http://msdn.microsoft.com/en-us/library/bb630352.aspx
Here are 2 different versions, one version for if all values are valid YYYYMMDD format, and one that will still work with invalid dates (but will return null for invalids).
DECLARE #tblTest TABLE (id int not null identity, myDate int not null)
INSERT INTO #tblTest(myDate)
VALUES(20140308),(20140410)
;
--QUERY 1: if all values in your table are valid dates, then you can use this
SELECT t.id, t.myDate
, myDateFormatted = CONVERT(varchar(10),CONVERT(DATE, CONVERT(VARCHAR(10),t.myDate)),101)
FROM #tblTest t
--NOW INSERT SOME INVALID DATES AS WELL
INSERT INTO #tblTest(myDate)
VALUES(20140132),(48)
;
--NOW IF THERE ARE INVALID DATE, THEN USING QUERY 1 WOULD CAUSE AN ERROR: Conversion failed when converting date and/or time from character string
--QUERY 2: if there are ANY invalid values in your table, then you can use this
SELECT t.id, t.myDate
, myDateFormatted =
CASE
WHEN ISDATE(t.mydate) = 1 and len(t.myDate) = 8
THEN CONVERT(varchar(10),CONVERT(DATE, CONVERT(VARCHAR(10),t.myDate)),101)
ELSE NULL --THIS IS AN INVALID DATE
END
FROM #tblTest t
;