SQL Converting character to datetime - sql-server

Does anybody now how to convert this character to date or datetime:
'10022011'

Quick & dirty:
select convert(datetime, stuff(stuff('10022011', 5,0,'-'),3,0,'-'))
However, you might want to consider converting the string into ISO standard date format:
declare #d char(8)
select #d = '10022011'
select convert(datetime, substring(#d,5,4) + '-' + substring(#d,3,2) + '-' + substring(#d, 1, 2))
in order to avoid ambiguity. 10-02-2011 has different meanings depending on which side of the pond you are.

SELECT convert(datetime, STUFF(STUFF('10022011',3,0,'-'),6,0,'-'), 103)
the number at the end is the Sql format you want the date to output

Related

SQL query to convert the value to MM/DD/YY and HH:MM:SS

My table TRANS contains T_STAMP column with the value '20170721154922' is a YYYYMMDDHHMMSS format. I am trying to write a query to display as MM/DD/YY in one column and HH:MM:SS in another column.
I am trying to convert this with the method CONVERT(VARCHAR(10),GETDATE(),10)
but I need full snippet to execute.
Could you help .
The following query can be return the exact format you required, the date as MM/DD/YY and time as HH:MM:SS:
SELECT CONVERT(VARCHAR(8), CONVERT(DATE, LEFT(T_STAMP, 8)), 1) AS DateValue,
CONVERT(VARCHAR(8), CONVERT(TIME,
SUBSTRING(T_STAMP, 9, 2) + ':'
+ SUBSTRING(T_STAMP, 11, 2) + ':'
+ SUBSTRING(T_STAMP, 13, 2)), 8) AS TimeValue
FROM Trans
Output:
DateValue | TimeValue
-----------|-----------
07/21/17 | 15:49:22
The following query will convert a value from the given format (YYYYMMDDHHMMSS) to DATE and TIME
DECLARE #T_STAMP NVARCHAR(100)='20170721154922'
SELECT CONVERT(DATE,LEFT(#T_STAMP,8)) T_DATE
,CONVERT(TIME,SUBSTRING(#T_STAMP,9,2)+':'
+SUBSTRING(#T_STAMP,11,2)+':'
+SUBSTRING(#T_STAMP,13,2)) T_TIME
As you mentioned the values are stored in YYYYMMDDHHMMSS format, so hope the values always be in fixed length (length 14).
Note:- As commented by Jens, Storing timestamps as formated strings is no good idea. Better store it in a timestamp datatype.
SELECT FORMAT(GETDATE() , 'MM/dd/yyyy HH:mm:ss')
the above would return something like this(21/07/2017 16:02:20).
select date_format(str_to_date('20170721154922', '%Y%m%d%H%S'), '%m%d%y');
'20170721154922' is a very very bad format to store date...
DECLARE #d varchar(14) = '20170721154922';
DECLARE #date DATETIME = CONVERT(datetime2, LEFT(#d, 8), 112);
DECLARE #time DATETIME = CONVERT(datetime2, CONCAT(SUBSTRING(#d, 9, 2), ':', SUBSTRING(#d, 11, 2), ':', SUBSTRING(#d, 13, 2)), 108);
SELECT FORMAT(#date, 'MM/dd/yy') date, FORMAT(#time, 'HH:mm:ss') time

Convert Oracle Datetime format query to MS SQL Server Format

I have a Oracle query
SELECT to_timestamp('29-03-17 03:58:34.312000000 PM','DD-MM-RR HH12:MI:SS.FF AM')
FROM DUAL
I want to convert to SQL Server where I need to retain the Oracle date string i.e '29-03-17 03:58:34.312000000 PM':
SELECT
CONVERT(DATETIME, REPLACE(REPLACE('29-03-2017 03:58:34.312000000 PM','-', '/'),'000000 ', ''), 131)
I tried the above query, as 131 format closely matches '29-03-17 03:58:34.312000000 PM' format 'dd/mm/yyyy hh:mi:ss:mmmAM' but only difference is with the year.
In Oracle year is 17 and SQL Server the year is 2017. I need to prefix 20 to the year to make it 2017. This query converts into Hijri datetime. I need it in Gregorian datetime format.
This is the documentation.
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
I need to convert the date which is in string in Oracle format to SQL Server equivalent. Is there any way where the format like 'dd/mm/yyyy hh:mi:ss:mmmAM' can be mentioned instead of mentioning the date format code like 131, 101, 102 in the convert function.
You might try it like this:
DECLARE #oracleDT VARCHAR(100)='29-03-17 03:58:34.312000000 PM';
SELECT CAST('<x>' + #oracleDT + '</x>' AS XML).value(N'(/x/text())[1]','datetime');
It seems, that XML is implicitly able to do this correctly...
EDIT: The above is culture related!
It worked on my (german) system, but if you set the correct dateformat you can force this (be aware of side effects for the current job!)
Try this and then remove the -- to try alternative date formats. Or try with GERMAN:
SET LANGUAGE ENGLISH;
SET DATEFORMAT mdy;
--SET DATEFORMAT ymd;
--SET DATEFORMAT dmy;
DECLARE #oracleDT VARCHAR(100)='01-02-03 03:58:34.312000000 PM';
SELECT CAST('<x>' + #oracleDT + '</x>' AS XML).value(N'(/x/text())[1]','datetime');
Another approach
You might split the string in all parts and build a convertible format like this:
DECLARE #oracleDT VARCHAR(100)='29-03-17 03:58:34.312000000 PM';
WITH AllParts(Casted) AS
(
SELECT CAST('<x>' + REPLACE(REPLACE(REPLACE(REPLACE(#oracleDT,'.','-'),' ','-'),':','-'),'-','</x><x>') + '</x>' AS XML)
)
SELECT CONVERT
(DATETIME,
DATENAME(MONTH,'2000'+Casted.value(N'x[2]/text()[1]','nvarchar(max)')+'01') + ' '
+ Casted.value(N'x[1]/text()[1]','nvarchar(max)') + ' '
+ N'20' + Casted.value(N'x[3]/text()[1]','nvarchar(max)') + ' '
+ Casted.value(N'x[4]/text()[1]','nvarchar(max)') + ':'
+ Casted.value(N'x[5]/text()[1]','nvarchar(max)') + ':'
+ Casted.value(N'x[6]/text()[1]','nvarchar(max)') + ':'
+ LEFT(Casted.value(N'x[7]/text()[1]','nvarchar(max)'),3)
+ Casted.value(N'x[8]/text()[1]','nvarchar(max)'),109)
FROM AllParts
Although I don't really understand the need to use a string format that does not suit conversion, but you could divide the string into parts then build it up by adding the parts to each other. The foundation part if the first 8 characters converted to datetime2 using format style 5.
select
t
, convert(varchar, converted ,121) converted
from (
select '29-03-17 03:58:34.312000000 PM' as t
) t
cross apply (
select
convert(datetime2,substring(t,1,8),5) dt2
, case when right(t,2) = 'PM' then convert(smallint,substring(t,10,2)) + 12
else convert(smallint,substring(t,10,2))
end hh
, convert(smallint,substring(t,13,2)) mi
, convert(smallint,substring(t,16,2)) ss
, convert(int,substring(t,19,9)) ns
) ca
cross apply (
select
dateadd(hh,hh,dateadd(mi,mi,dateadd(ss,ss,dateadd(ns,ns,dt2))))
as converted
) ca2
;
Note I am able to use the column aliases of the first cross apply (dt1, hh, mi, ss, ns) in the second cross apply to form the converted datetime2 value.
+--------------------------------+-----------------------------+
| t | converted |
+--------------------------------+-----------------------------+
| 29-03-17 03:58:34.312000000 PM | 2017-03-29 15:58:34.3120000 |
+--------------------------------+-----------------------------+
see: http://rextester.com/DZJ42703

SQL Server: Transfer YYYYMMDD-HHMMSS to mm/dd/yyyy hh:mm:ss

My SQL Server system is 2016.
As topic, I want to convert YYYYMMDD-HHMMSS to mm/dd/yyyy hh:mm:ss, and use dynamic SQL to fulfill this.
My data looks like this:
ID
20161119-075950
20161117-110952
20161118-153406
The datatype is nvarchar.
While I used the syntax below:
SELECT convert(date,convert(varchar(max),id,130), 130) from abc
An error Conversion failed when converting date and/or time from character string. shows up. I am thinking whether it is because SQL Server cannot identify this YYYYMMDD-HHMMSS as date type, and I need to convert this to YYYYMMDD hh:mm:ss first and then mm/dd/yyyy hh:mm:ss? Feel free to shed some lights. Thanks!
Select CONVERT(VARCHAR(25) , CAST(LEFT(ID , 8) AS DATETIME), 101)
+ ' ' + LEFT(RIGHT(ID , 6) ,2) + ':'
+ SUBSTRING(RIGHT(ID , 6) , 3,2) + ':'
+ RIGHT(ID , 2)
FROM TableName
Try it like this
DECLARE #tbl TABLE(ID NVARCHAR(100));
INSERT INTO #tbl VALUES
('20161119-075950')
,('20161117-110952')
,('20161118-153406');
--This is the actual select you need:
SELECT CAST(LEFT(ID,8) AS DATETIME) + STUFF(STUFF(RIGHT(ID,6),5,0,':'),3,0,':')
FROM #tbl
Your first part is strictly 8 chars long and implicitly casteable (unseperated datetime yyyymmdd). The time part is strictly 6 chars long. I use STUFF to insert the colons. This time can be added to a DATETIME. It will be - again implicitly - casted to DATETIME.
EDIT
To reach the given format you stated in the title just convert the first part first with code 101:
SELECT CONVERT(VARCHAR(10),CAST(LEFT(ID,8) AS DATETIME),101) + ' ' + STUFF(STUFF(RIGHT(ID,6),5,0,':'),3,0,':')
FROM #tbl
This should get the format you want... but there are probably better ways.
select
convert(varchar(16),convert(date,left(ID,8)),101) +
' ' +
substring(substring(ID,10,6),1,2) +
':' +
substring(substring(ID,10,6),3,2) +
':' + substring(substring(ID,10,6),5,2)

T-SQL : separating datetime into date and time and then converting to numeric

My requirement is much more specific than what I found - I have a table that stores a datetime value. I need to retrieve that value, separate it into a date and a time, and then convert both those values into integer values. This is the field I'm trying to retrieve:
release_date = 2016-06-28 07:04:17.960
This needs to be split like so:
--numeric date as yyyymmdd from above value would be:
#my_numeric_date = 20160628
--numeric time as hhmmss from above value would be:
#my_numeric_time = 70417
Is there a relatively straightforward way of achieving this?
The last time I needed this, I used these two statements:
CONVERT(INTEGER, CONVERT(VARCHAR, release_date, 112)),
CONVERT(INTEGER, REPLACE(CONVERT(VARCHAR, release_date, 108), ':', ''))
So, to save it in variables use:
SELECT
#my_numeric_date = CONVERT(INTEGER, CONVERT(VARCHAR, release_date, 112)),
#my_numeric_time = CONVERT(INTEGER, REPLACE(CONVERT(VARCHAR, release_date, 108), ':', ''))
Declare #Date DateTime = GetDate()
Select DateInt = (Year(#Date)*10000)+(Month(#Date)*100)+Day(#Date)
,TimeInt = (DatePart(HH,#Date)*10000)+(DatePart(MINUTE,#Date)*100)+DatePart(SECOND,#Date)
Returns
DateInt TimeInt
20160628 104510
-- The DateTime was 2016-06-28 10:45:10.017

How to solve the date comparison issue in SQL Server?

I am using the following way to compare two dates:
if CONVERT(varchar(20), #ScheduleDate, 101) >= CONVERT(varchar(20), #CurrentDateTime, 101)
This is working fine for the current year, but when the comes in yearly like one date is 12/31/2012 and 1/1/2013 then its not working.
Please help me how can I resolve this.
why do you comparing strings?
you can compare dates
if #ScheduleDate >= #CurrentDateTime
but if your date contains time, I usually do
if convert(nvarchar(8), #ScheduleDate, 112) >= convert(nvarchar(8), #CurrentDateTime, 112)
112 datetime format is YYYYMMDD so it's good for compare dates
You have to remember that string comparison is from left to right, so "1/...." is smaller than "12/...".
You need to use DATETIME comparisons, not string comparison.
Something like
DECLARE #ScheduleDate DATETIME = '1/1/2013',
#CurrentDateTime DATETIME = '12/31/2012'
IF (#ScheduleDate >= #CurrentDateTime)
BEGIN
SELECT #ScheduleDate, #CurrentDateTime
END
DECLARE #ScheduleDateString VARCHAR(20) = '1/1/2013',
#CurrentDateTimeString VARCHAR(20) = '12/31/2012'
IF (CONVERT(DATETIME,#ScheduleDateString,101)>=CONVERT(DATETIME,#CurrentDateTimeString,101))
BEGIN
SELECT CONVERT(DATETIME,#ScheduleDateString,101),CONVERT(DATETIME,#CurrentDateTimeString,101)
END
SQL Fiddle DEMO
Note that if the variables are already datetimes, you do not need to convert them.
Assuming that both variables are currently DateTime variables, can't you just compare them without converting to strings?
declare #ScheduleDate DATETIME, #CurrentDateTime DATETIME
SET #ScheduleDate = '1 Jan 2013'
SET #CurrentDateTime = GetDate()
IF (#ScheduleDate >= #CurrentDateTime)
BEGIN
SELECT 'Do Something'
END
ELSE
BEGIN
SELECT 'Do Something Else'
END
when you use CONVERT(nvarchar(8), #ScheduleDate, 112) function it's return string instead of date.
so,
Use "112" DateFormat in Sql Server it's return string in "YMD" format without any sepration.
compare that string in your query and get desire output.
Such as "if CONVERT(nvarchar(8), #ScheduleDate, 112) >= CONVERT(nvarchar(8), #CurrentDateTime, 112)"
I would not use CONVERT to compare formatted strings. It is slow (well, more like microseconds, but still)
I use a UDF for SQL prior to version 2008
CREATE FUNCTION [dbo].[DateOnly] (#Date DateTime)
RETURNS Datetime AS
BEGIN
Return cast (floor (cast (#Date as float)) as DateTime)
END
and for versions >=2008 this approach
select convert(#MyDateTime as DATE)
Of course, you can compare datetime values directly, but to know whether two datetime values are on the same date (ignoring the time component), the above versions have proven to be effectivy.
Date : From and To with following format
from_Date# = #dateformat("#form.from#", "mm/dd/yyyy")
to_Date# = #dateformat("#now()#" + 1, "mm/dd/yyyy")
In SQL Statement
WHERE a.DateCreated >= CAST ('#from_date#' AS DATE) and a.DateCreated <= CAST('#to_date#' AS DATE)
This is working fine without any cast of original date time column

Resources