how to get custom date time format in sql - sql-server

I am trying to convert Date Time in Sql,
I want format like this :- DD-MM-yyyy 00:00 (24 Hours) for example :- 12-Nov-2014 00:00
I tried this: CONVERT(varchar(16), IFD.dtDateOfIncident, 113) As EventDate , but I don't get success and I have also refer this http://www.sql-server-helper.com/tips/date-formats.aspx , but I can't find any method or keyword.
Please Help me
Regards,
Vinit

declare #dt varchar(20) = '12-Nov-2014 24:59'
Select Replace(Convert(varchar(17),GETDATE(),106),' ','-') + ' ' + Convert( varchar(5) , GETDATE(),108)

Problen with varchar(16). The varchar length must be 17 to achieve your requirement.
CONVERT(varchar(17), IFD.dtDateOfIncident, 113)
SELECT REPLACE(CONVERT(varchar(11), IFD.dtDateOfIncident, 106) , ' ', '-')
+ ' ' + CONVERT(varchar(5), IFD.dtDateOfIncident, 108)

Try this. You can use either 13 or 113 in Convert Function . Increase the length of your varchar in convert
select convert(varchar(30),GETDATE(),113) --19 Nov 2014 11:26:46:420
select convert(varchar(30),GETDATE(),13) --19 Nov 2014 11:26:46:420
Update : To get - in date
select replace(left(convert(varchar(30),GETDATE(),113),11),' ','-')+RIGHT(convert(varchar(30),GETDATE(),113),13)
Output : 19-Nov-2014 11:32:17:890

Try the below query if U are using SQL server 2008 and above
select replace(convert(varchar(17),IFD.dtDateOfIncident,106), ' ','-') + ' ' +
Cast(convert(Time(0),GETDATE(),108) as Varchar) As EventDate
or
try this for SQL server 2000 and above
select replace(convert(varchar(17),IFD.dtDateOfIncident,106), ' ','-') + ' ' +
convert(Vacrhar(8),IFD.dtDateOfIncident,108) As EventDate
The above queries will display the reuslt like
19-Nov-2014 11:10:45

Don't do this in SQL. Do it in whatever language you are using in the front end application. If your presentation layer is web, use Moment.js
moment().format('DD-MM-YYYY, HH:mm');
In C# you might do it like this
DateTime.Now.ToString("dd-MM-yyyy HH:mm")
Formatting for display is a presentation layer consideration.

Related

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)

SQL Server query: Concatenating two strings and converting to datetime changes the format thereby Datedifference calculated is wrong

Below is the query which I am trying to run:
SELECT
CONVERT(DATETIME,('12/1/2016' +' '+ '2:00:00')) AS A,
CONVERT(DATETIME,('12/1/2016' +' '+ '2:00:00')) AS B,
DATEDIFF(HOUR, CONVERT(DATETIME, ('12/1/2016' + ' ' + '2:00:00')), CONVERT(DATETIME, ('12/1/2016' + ' ' + '2:00:00'))) as DateDiffernce
Output is:
A B DateDiffernce
2016-12-01 02:00:00.000 2016-12-01 02:00:00.000 0
Let's take 12/1/2016 here the format is DD/MM/YYYY. After using convert function it is getting changed to YYYY-MM-DD which is fine the problem is places are changed i.e 12/1/2016 to 2016-12-01 12 which was the date is shifted or considered as month - which should not happen.
I even tried another query to restrict this conversion which didn't help:
SELECT
CONVERT(DATETIME, CONVERT(CHAR(10), '12/1/2016', 112)
+ ' ' + CONVERT(CHAR(8), '2:00:00', 108))
Kindly help..
Please check #Panagiotis Kanavos comment. He is right. Your query would work fine. Please change the time value like the below to get the DateDifference value.
SELECT CONVERT(DATETIME, ('13/1/2016' + ' ' + '2:00:00'),103) AS A
,CONVERT(DATETIME, ('13/1/2016' + ' ' + '13:00:00'),103) AS B
,DATEDIFF(HOUR, CONVERT(DATETIME, ('13/1/2016' + ' ' + '2:00:00'),103), CONVERT(DATETIME, ('13/1/2016' + ' ' + '13:00:00'),103)) AS DateDiffernce
Hello All Thankyou for your inputs, i was able to solve the issue by
using following code
SET DATEFORMAT YDM
Cheers!! Enjoy coding

SQL Server: Convert a month name (string) to a date

I have a table with a month name in it as type varchar. e.g. "November". Can I convert this to a date field?
CONVERT(DATETIME,main.ReportMonth) AS ReportMonthDate
CAST(main.ReportMonth AS DATETIME) AS ReportMonthDate
both result in a conversion failure.
I'm using SQL Server 2008.
You can hard code a string value at the end of your input value. Something like this.
declare #ReportMonth varchar(10) = 'November'
select cast(#ReportMonth + ' 1, 2015' as date)
Or if you want to make the year portion be dynamic based on the current date you could modify that slightly like this.
select cast(#ReportMonth + ' 1, ' + cast(datepart(year, getdate()) as char(4)) as date)

sql-server: Convert Char(14) to Datetime?

With SQL-server 2008 database I have a char(14) data type that I want to convert to a datetime.
Example char(14) values:
20120209102026
20010131120000
The date format is yyyymmdd of some sort.
It seems like the values I posted are not the only format, because I get an "index out of range" error for some of the values. For this I can skip the ones that are not valid dates.
declare #c char(14)
select #c='20120209102026'
Select Cast(Substring(#c,1,8) + ' ' + Substring(#c,9,2)+':'+
Substring(#c,11,2)+':'+ Substring(#c,13,2) as DateTime)
Second Version that ignores out of range numeric values:
Select Cast(
Rtrim(Substring(#c,1,8)
+ Case When len(Substring(#c,9,4))>=4 then +' '+ Substring(#c,9,2) else '' end
+ Case When len(Substring(#c,11,2))=2 then +':'+ Substring(#c,11,2) else '' end
+ Case When len(Substring(#c,13,2))=2 then +':'+ Substring(#c,13,2) else '' end)
as Datetime)
This is ugly but if your format is yyyymmddhhmmss then you can use:
select cast(left(yourDate, 8)+' '+
SUBSTRING(yourDate, 9, 2)+':'+SUBSTRING(yourDate, 11, 2)+':'+RIGHT(yourDate, 2) as datetime)
from yourtable
See SQL Fiddle with Demo
A series of function calls but ends up with the same outcome.
Try like this:
select convert(datetime,STUFF(STUFF(STUFF(STUFF(STUFF('20010131120000',5,0,'/'),8,0,'/'),11,0,' '),14,0,':'),17,0,':'))
Look here for how STUFF works!

Resources