Conversion of datetime to nvarchar(8) in T-SQL - sql

I'm trying to convert a datetime column to ISO format, as yyyymmdd. For example, I would like to be able to convert '13 dec 2018' to '20181213'.
According to Microsoft's T-SQL Docs, I should be able to do this using
convert(nvarchar(8), '13 dec 2018', 112)
however this doesn't work - I get the result '13 dec 2', which looks to be nothing more than the original string cut down to 8 characters.
I have also tried using
convert(datetime, '13 dec 2018', 112)
which gives me the result of 'Dec 13 2018 12:00AM' - again, nothing like what the function is supposed to produce.
What I am doing wrong? I could solve the problem easily enough using datepart() and concatenated strings, but I'd rather use the more elegant approach if possible.

Combine them:
convert(nvarchar(8), convert(datetime, '13 dec 2018'), 112)
I don't recommend using the format 112 for the first conversion, because it is misleading. SQL Server is very good at converting without a format. If you do use one the appropriate one is 106.

I figured it out - because I was entering the date as a string, and not converting it to a datetime value first, it was treating my date as if it were a string. When I handle it this way:
convert(nvarchar(8), cast('13 dec 2018' as datetime), 112)
I get the expected result, '20181213'.

select convert(nvarchar(8), cast(GETDATE() as datetime), 112) as TodayDate

YYYYMMDD format can obtain by datetime to varchar format.
select convert(varchar(8),convert(datetime, '13 dec 2018'),112)
The above query provides the required result

Related

Converting datetime not converting datetime

So I have a table and I am trying to convert the time from its current format that looks like this
Sep 17 2020 1:07AM
to
2020-09-16 20:07:00.000
if I try to update the entire table by
UPDATE
OOTYPE
SET
OOTYPE.LastModified = CONVERT(DATETIME, SWITCHOFFSET(CONVERT(DATETIMEOFFSET, LastModified),
DATENAME(TzOffset, SYSDATETIMEOFFSET())))
it runs successfully but the times are still in the format
Sep 17 2020 1:07AM
However, if I just run a simple select statement to show it changed
SELECT CONVERT(DATETIME, SWITCHOFFSET(CONVERT(DATETIMEOFFSET,lastmodified), DATENAME(TzOffset, SYSDATETIMEOFFSET()))) FROM [OOTYPE]
The output is exactly what I'm looking for.....
2020-09-16 20:07:00.000
Anyone have any idea where I'm screwing this simple change up at, I have put an embarrassing amount of time into this....
If I follow you correctly:
SELECT CONVERT(varchar, CONVERT(datetime, 'Sep 17 2020 1:07AM'), 121)
You should use convert style 121 which is yyyy-mm-dd hh:mi:ss.mmm.

Convert string into date in SQL Server

Conversion failed when converting date and/or time from character string.
I'm getting the above error when running this statement in SQL Server:
SELECT CONVERT(datetime, 'Fri, 15 Jan 2016 17:30:05 GMT')
Actually I want to insert same string format in Datetime column
As suggested by Tim Biegeleisen, that string needs to be processed to be converted. In order to convert it you need to strip of the day (Fri,) and the GMT timezone at the end, for example:
DECLARE #date varchar(50) = 'Fri, 15 Jan 2016 17:30:05 GMT'
SELECT CONVERT(DATETIME, SUBSTRING(#date, 5, LEN(#date) - 8), 113)
This solution does strip the timezone information, have a look at this post if you want to convert it back to UTC.
If you want to insert the string 'Fri, 15 Jan 2016 17:30:05 GMT' into datetime column then you need to remove Fri, and GMT from the string before inserting.
SELECT CAST(substring(#str_date,5,len(#str_date)-8) as datetime)
DEMO

How to format date in DD-MMM-YYYY format eg 29-JAN-2015?

I want the date in DD-MMM-YYYY format eg 29-JAN-2015.
I have tried with:
SELECT TRIM(TO_DATE('29 Jan 2015'
,'DD MON YY')) FROM DUAL
I got result as: 29-JAN-15
But I am expecting: 29-JAN-2015 in date format not in char format
Im assuming Oracle DB:
select to_char(SYSDATE, 'dd-Mon-yyyy') from dual
Returns
29-Jan-2015
Thanks for answers.
I got the solution. First we need to alter the session as below:
alter session set nls_date_format='DD-MON-YYYY';
then run the query:
SELECT TRIM(TO_DATE('29 Jan 2015'
,'DD MON YYYY'))
FROM DUAL
Now I got result as:29-JAN-2015
What you are doing is take the string '29 Jan 2015' and make it a date using the format 'DD MON YY'. This should fail of course for '2015' not matching 'yy', but Oracle is lenient here.
Then you use TRIM on the date. But TRIM is for strings. What happens is that you get shown '29 Jan 15'. I am getting shown '29.01.15' instead of the usual '29.01.2015'. However the behavior: Don't use TRIM on dates, its behavior is nowhere specified as far as I am aware. Use TO_CHAR to format a date in output.
If you only select a date without TO_CHAR you get the date shown in some standard format, which can be '29 Jan 2015' or '29 Jan 15' or '29.01.2015' or '01/29/2015' depending on the app you are using and possibly some setting therin.
For completeness sake:
TO_DATE takes a string ('29 Jan 2015' in your case) and converts it to a date. If the string contains names, make sure that you specify the appropriate language setting:
TO_DATE('29 Jan 2015', 'dd mon yyyy', ''NLS_DATE_LANGUAGE=AMERICAN')
To get a formatted string from a date, use TO_CHAR:
TO_CHAR(sysdate, 'dd MON yyyy', 'NLS_DATE_LANGUAGE=AMERICAN')
Usually you don't do that, however. You select a date as is and have your app (written in PHP, Java or whatever) care about how to display it appropriately to the user's computer's settings.
In SQL Server the query
select CONVERT(nvarchar, GETDATE(), 106) as [Converted Date]
returns:
29 Jan 2015
Manu is correct. Oracle publish a full list of date format specifiers.
http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#CDEHIFJA
Use CONVERT(VARCHAR(11),GETDATE(),106)
See detailed explanation here:
http://www.w3schools.com/sql/func_convert.asp
Can you try:
SELECT TRIM(TO_DATE(SYSDATE ,'DD MON YYYY')) FROM DUAL
YY will only show 2 ciphers, instead of YYYY that will show 4.

Need to identify number that is higher than a given date

I have a date column in a table. The date column is in varchar. I want to identify a particular date range from that date column. My query is like this:
SELECT *
FROM [003 AccptReg].[dbo].[SysData1]
WHERE [RegDate_Sys] > '18 jul 2013'
But the result is not giving accurate result, i.e. it gives dates which are prior of 18 jul 2013.
Is there any thing wrong I am doing?
For date column, you should compare as DATE
select * from [003 AccptReg].[dbo].[SysData1]
where CAST([RegDate_Sys] AS DATE) > CAST('18 jul 2013' AS DATE)
The problem is that you have the date as a varchar, and doesn't convert it to a date when you are doing the comparison. The database doesn't know that you see the data as dates, and will simply compare them as strings, so for example '2 jan 1736' will be larger than '18 jul 2013' because 2 comes after 1.
The best would be if you could store the data as datetime values (or date), then you don't need to do the conversion when you compare the values, which would give better performance.
If that's not possible, do the conversion in the query:
select * from [003 AccptReg].[dbo].[SysData1]
where convert(datetime, [RegDate_Sys], 106) > '18 jul 2013'
Depending on the settings on the server, you might also need to convert '18 jul 2013' in the same way for the database to understand it correctly as a date.
Convert the date to datetime format and then compare:
select * from [003 AccptReg].[dbo].[SysData1]
where convert(datetime,[RegDate_Sys]) >convert(datetime,'18 jul 2013')

How to extract date from datetime stored as a varchar

How can I convert the string 'Fri, 9 Mar 2012 10:43:21 +0000 (UTC)', stored as a varchar(max), to the datetime value '09-03-2012', which is the date part of the string?
Use convert and reference to this page http://msdn.microsoft.com/en-us/library/ms187928.aspx
e.g.
CONVERT(varchar(8), GETDATE(), 112)
According to MS: http://msdn.microsoft.com/en-us/library/ms187928.aspx
The CONVERT() function is a general function that converts an expression of one data type to another.
The CONVERT() function can be used to display date/time data in different formats.
and the table lists 105 as the code for the style you want.
So, for your example date:
CONVERT(VARCHAR(10), 'Fri, 9 Mar 2012 10:43:21 +0000 (UTC)', 105)
should probably do the trick.
I had to chop up your date first, but here goes:
DECLARE #ds varchar(30)='Fri, 9 Mar 2012 10:43:21 +0000 (UTC)';
SELECT CONVERT(VARCHAR(10)
,CAST(SUBSTRING(#ds
,CHARINDEX(' ',#ds)
,LEN(#ds)-(PATINDEX('%[0-9][0-9][0-9][0-9]%',#ds)+6))
AS DATETIME)
,105
)
Result:
09-03-2012
If you have SQL Server 2012, you can try this:
select CONVERT(date, TRY_PARSE('Fri, 9 Mar 2012 10:43:21 +0000' AS datetime2))
NOTE: (UTC) is removed, it didn't parse correctly.
Also, be aware if you need to localize that time value. For example, I live in AZ, so typically I just subtract -7 hrs from UTC times to localize. You will need to make similar adjustments based on the time zone