converting varchar to date format - sql

I have 2 fields date_issued and time_issued as below
date_issued time_issued
1031 225225 (22 hrs 52 mins 25 secs)
I need to convert that varchar value to datetime as dd-mm-yy h:m:s
I tried following
select CONVERT(datetime, date_issued+time_issued ,120) as ttt from tbl
but is showing following error
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting datetime from character string.
Any ideas??

Assuming year is 2012:
select CONVERT(datetime, '2012' + LEFT(date_issued, 2) + RIGHT(date_issued, 2) + ' ' + LEFT(time_issued, 2) + ':' + SUBSTRING(time_issued, 3, 2) + ':' + right(time_issued, 2))

Well, first of all.
U have an obvious error. If those columns are numbers (not strings) you are adding them up and that is plainly wrong.
Second, if those are strings, you are missing a year in date area and you are missing : in time area.
Third, you need to add a ' ' between those 2.
in my example
SELECT convert(datetime,'20091231 12:12:12') FROM DUAL
i get
2009-12-31 12:12:12.000
P.S. Yes, i have DUAL in SQL server, this wasn't ran in Oracle.

Here is one way, you can remove REPLICATE if the data includes leading zeros, else it is needed for padding to discriminate the date parts.
select
cast (
stuff(replicate('0', 4 - len(date_issued)) + date_issued, 3, 0, '/') + '/2012'
+ ' ' +
stuff(stuff(replicate('0', 6 - len(time_issued)) + time_issued, 3, 0, ':'), 6 ,0 ,':')
as datetime)

Related

Change date format for char data type

I have columns with ddmmyyyy in char format.
Date
10112021
11112021
12112021
I want to change that records into yyyymmdd
expected like these
Date
20211110
20211111
20211112
I tried many queries like
convert(varchar,DATE, 112) as DATE
but the result is still ddmmyyyy format
and
tried also like this
convert(varchar, cast(DATE as date), 112) as DATE
But the result is
Conversion failed when converting date and/or time from character string
any suggestions?
The key problem is that you are storing your date value as a string. You should never do that because it will almost always result in problems further down the line.
Therefore to change the formatting you first have to convert your current string into a valid date and then you use convert to format it as you desire.
SELECT [Date]
-- First convert to a valid date time - the current format needs to be modified
, CONVERT(DATE, SUBSTRING([DATE], 1, 2) + '-' + SUBSTRING([DATE], 3, 2) + '-' + SUBSTRING([DATE], 5, 4), 105) [Proper Date Value]
-- Then convert back to a string in the desired format
, CONVERT(VARCHAR(8), CONVERT(DATETIME, SUBSTRING([DATE], 1, 2) + '-' + SUBSTRING([DATE], 3, 2) + '-' + SUBSTRING([DATE], 5, 4), 105), 112) [Formatted Date Value]
-- In fact you can actually just use direct string manipulation in this case
, SUBSTRING([DATE], 5, 4) + SUBSTRING([DATE], 3, 2) + SUBSTRING([DATE], 1, 2)
FROM (
VALUES
('10112021'),
('11112021'),
('12112021')
) AS D ([Date]);
Returns:
Date
Proper Date Value
Formatted Date Value 1
Formatted Date Value 2
10112021
2021-11-10
20211110
20211110
11112021
2021-11-11
20211111
20211111
12112021
2021-11-12
20211112
20211112
Note: You should never use varchar without a length as in many circumstances it defaults to a length of 1 which is then the cause of many hard to find issues.

Convert nvarchar date (DD/MM/YYYY) to Date Period (YYYY_MM)

I am trying to convert this into a period format, so e.g. 2018_05 (YYYY_MM). currently the data is in DD/MM/YYYY format.
I tried a cast code but it returns me YYYY_DD.
SELECT
CASE WHEN RESERVED_FIELD_4 IS NULL THEN NULL
ELSE cast(year(RESERVED_FIELD_4) as Nvarchar (4))
+'_'+right('00'+cast(month(RESERVED_FIELD_4) as Nvarchar (2)),2)
END AS [DATAFEED_PERIOD]
I expect/want to see YYYY_MM.
Assuming RESERVED_FIELD_4 is a string type (char/nchar/varchar/nvarchar) the simplest solution would be to use substring:
CASE
WHEN RESERVED_FIELD_4 IS NULL THEN NULL
ELSE SUBSTRING(RESERVED_FIELD_4, 7, 4) + '_'+ SUBSTRING(RESERVED_FIELD_4, 4, 2)
END AS [DATAFEED_PERIOD]
If it's a date/datetime/datetime2 data type, the simplest solution would be to use format:
FORMAT(RESERVED_FIELD_4, 'yyyy_MM')
But for better performance you can use convert and stuff:
SELECT STUFF(CONVERT(char(6), RESERVED_FIELD_4, 112), 5, 0, '_')
In case your format is actually d/m/y the simplest option is to convert to date and than back to string:
SELECT STUFF(CONVERT(char(6), CONVERT(Date, RESERVED_FIELD_4, 103), 112), 5, 0, '_')
This is the common problem of storing a date with a VARCHAR column. You are guessing that the stored pattern is DD/MM/YYYY but the SQL engine doesn't know that and is currently assuming the MM/DD/YYYY pattern.
Please check these results:
-- MM/DD/YYYY
SELECT
DAY ('05/01/2019'), -- 1
MONTH('05/01/2019') -- 5
-- DD/MM/YYYY
SELECT
DAY ('25/05/2019'), -- Conversion failed when converting date and/or time from character string
MONTH('25/05/2019') -- Conversion failed when converting date and/or time from character string.
To display what you want correctly use string functions:
SELECT
RIGHT(RESERVED_FIELD_4, 4) + '_' + SUBSTRING(RESERVED_FIELD_4, 4, 2)
But you should actually fix the values on your VARCHAR column, cast them to DATE and store the values as DATE.
ALTER TABLE YourTable ADD ReservedField4Date DATE
UPDATE YourTable SET
ReservedField4Date = CONVERT(DATE,
RIGHT(RESERVED_FIELD_4, 4) -- Year
+ '-' + SUBSTRING(RESERVED_FIELD_4, 4, 2) -- Month
+ '-' + LEFT(RESERVED_FIELD_4, 2)) -- Day
ALTER TABLE YourTable DROP COLUMN RESERVED_FIELD_4
EXEC sp_rename 'SchemaName.YourTable.ReservedField4Date', 'RESERVED_FIELD_4', 'COLUMN'
Beware that changing the column type might affect other queries that assume this is a VARCHAR column.
If your data is in DD/MM/YYYY format, then it is being stored as a string. Hence, string functions come to mind:
select right(RESERVED_FIELD_4) + '_' + substrint(RESERVED_FIELD_4, 4, 2)
In SQL-SERVER you can use 'format'
format(dy,#your_date) as day_of_year
month(#your_date) as month
Try this:
Select concat(month(#your_date),'_'year(#your_date)) as your_period
this is a reference
Why not just do conversations ? :
SELECT REPLACE(CONVERT(VARCHAR(7), CONVERT(date, RESERVED_FIELD_4, 101), 102), '.', '_')
This assumes RESERVED_FIELD_4 is date type.

sql convert string to date/datetime

My Filename column looks like 'D181115.T000000'. I used the following code to make it a string, looks like '2018-11-15'.
select '20' + substring(filename, 2,2) + '-' + substring(filename, 4,2) + '-' + substring(filename,6,2)
from table_name
Then I want to convert the string to date type (because I need to sort by date)
select convert(datetime, '20 + substring(filename, 2,2) + '-' + substring(filename, 4,2) + '-' + substring(filename,6,2)')
from table_name
Then I got this error message:
The data types varchar and varchar are incompatible in the subtract
operator.
Any help will be greatly appreciated!
I suspet the database is SQL Server. In that case one can use just
select cast('20' + substring('D181115.T000000', 2,6) as date)
or
select try_cast('20' + substring('D181115.T000000', 2,6) as date)
YYYYMMDD is one of the two unambiguous date formats. The other is the full ISO8601 date+time format. YYYY-MM-DD on the other hand depends on the DATEFORMAT setting
Update
I'd suggest performing this conversion as part of data loading though. Applying functions to a field prevents the server from using any indexes that cover the field. The server will have to scan the entire table in order to produce the final values used for filtering and sorting.
At least consider addd an indexed computed column that produces the file date
I want to convert the string to date type
Look at the first and 2nd statements you included, they are different in that you are missing a quote and you added an extra quote in the second one.
declare #filename varchar(20) = 'D181115.T000000'
select convert(datetime, '20' + substring(#filename, 2,2) + '-' + substring(#filename, 4,2) + '-' + substring(#filename,6,2))
Produces output:
2018-11-15 00:00:00.000

Turn string with date and time to hh:mm

I have a string field in my table with date and time. Like this
20131001094049
Now i have to get the hour and Minute out of this like 09:40.
How can i easily get that?
I am going to assume, based on your string that the format is YYYYMMDDHHMMSS (Year,Month,Day,Hour,Minute,Second). This solution is for SQL Server.
Considering that you could go for the poor man fix of string manipulation.
SELECT
LEFT(RIGHT(20131001094049, 6 ) , 2) + ':' +
RIGHT(LEFT(RIGHT(20131001094049, 6 ) , 4),2)
Which returns 09:40
What happens is it takes the original date, 20131001094049, takes the right six characters 094049 and then the left two 09. Then it concatenates that to a : and then concatenates the resulting string to 04 of the assumed MM(Minutes) section.
Because your date and time information is not stored in a standard DateTime format for direct conversion, you will need to rely on string manipulation i.e:
SELECT SUBSTRING('20131001094049', 9, 2) + ':' +
SUBSTRING('20131001094049', 11, 2)
To return a full DateTime type you could manipulate the whole string and use the FORMAT function (available in SQL Server 2012 or greater):
DECLARE #dt nvarchar(50), #newdt nvarchar(50)
SET #dt = '20131001094049'
SET #newdt = SUBSTRING(#dt, 1, 4) + '-' + SUBSTRING(#dt, 5, 2) + '-' + SUBSTRING(#dt, 7, 2) + ' ' + SUBSTRING(#dt, 9, 2) + ':' + SUBSTRING(#dt, 11, 2) + ':' + SUBSTRING(#dt, 13, 2)
SELECT FORMAT(CONVERT(datetime, #newdt), 'HH:mm')
Both will return 09:40

SQL Change format of datetime to specific style

I'm trying to convert a datetime value to a specific format, but noe of the style codes seem to do what I want. I tried the SQLUSA post on style codes, but none of them are quite right.
I have a column where the date/time is stored as yyyy-mm-dd hh:nn:ss (24 hour time)
I have a select statement were I want to take this column, but express the date as: mm/dd/yyyy hh:nn:ss AM/PM
The closest I've come is:
CONVERT(varchar,[datetimecolum],22) AS [newcolumnname]
but that only gives me a 2 digit year, not a century year (yyyy).
Any ideas? I'm totally lost. :(
Firstly, datetime fields are not stored in a specific string format, or but as a serial number. So what you see on screen is not what is stored but rather your database tool's default rendering of the date. Secondly why are you doing this in SQL? If you're passing the value to an application, make the conversion there from a native type. Thirdly, I don't think 22 is a valid conversion code in TSQL. Check http://msdn.microsoft.com/en-us/library/ms187928.aspx, for more info.
From: http://msdn.microsoft.com/en-us/library/ms187928.aspx
Judging by all the other formats listed, it would infer just add 100 to the format number to get "with century" (yyyy).
Although according to the documentation (and my tests) there is no format 22 (or 122) - so you'll have to combine two other formats to get exactly what you need:
CONVERT(varchar,[datetimecolum],101) + ' ' + CONVERT(varchar,[datetimecolum],108) AS [newcolumnname]
SQLFiddle demo
I think this does it
select stuff(convert(varchar(20),getdate(),22),7,2,
CAST( DATEPART(yyyy,getdate()) as CHAR(4)))
This is close but no AM PM
select convert(varchar(100),getdate(),22),
+ ' ' + CAST(DATEPART(mm,getdate()) as CHAR(2))
+ '/' + CAST( DATEPART(dd,getdate()) as CHAR(2))
+ '/' + CAST( DATEPART(yyyy,getdate()) as CHAR(4))
+ ' ' + CAST(DATEPART(HH,getdate()) as CHAR(2))
+ ':' + CAST(DATEPART(mi,getdate()) as CHAR(2))
+ ':' + CAST(DATEPART(ss,getdate()) as CHAR(2))
This is a Even clunkier than my original, but it works, except you won't get leading zeros for hours or minutes. You could modify this code to do that as well, but it will get really messy then, so I leave that to you ;-)
In other words, if the date + time is
3/1/2012 10:01:35 PM,
you will instead get:
3/1/2012 10:1:35 PM
Irritating, eh?
Anyway, here you go. Hope this helps.
SELECT dt.ID,
CASE WHEN EXISTS(SELECT DATEPART(HH, mt.TheDate)
FROM MyTable AS mt
WHERE mt.ID = dt.ID
AND (DATEPART(HH, mt.TheDate)) > 12)
THEN
(SELECT
CONVERT(varchar,(MONTH(dt.TheDate))) + '/' +
CONVERT(varchar,(DAY(dt.TheDate))) + '/' +
CONVERT(varchar,(YEAR(dt.TheDate))) + ' ' +
CONVERT(varchar, DATEPART(HH, dt.TheDate)-12) + ':' +
CONVERT(varchar,(DATEPART(mi, dt.TheDate))) + ':' +
CONVERT(varchar,(DATEPART( ss, dt.TheDate))) + ' PM')
ELSE
(SELECT
CONVERT(varchar,(MONTH(dt.TheDate))) + '/' +
CONVERT(varchar,(DAY(dt.TheDate))) + '/' +
CONVERT(varchar,(YEAR(dt.TheDate))) + ' ' +
CONVERT(varchar, DATEPART(HH, dt.TheDate)) + ':' +
CONVERT(varchar,(DATEPART(mi, dt.TheDate))) + ':' +
CONVERT(varchar,(DATEPART( ss, dt.TheDate))) + ' AM') END As FullDate
FROM MyTable AS dt
you need to do it in 2 parts and you need to use stuff to remove millisecond.I will update if find an other way to get rid of millisecond
SELECT CONVERT(VARCHAR(10), GETDATE(), 101)+' '+STUFF(RIGHT(CONVERT(VARCHAR(26), GETDATE(), 109),14),9,4,'')
output : 09/13/2012 11:15:21PM
Edit: incase you want space before AM/PM then use ' ' instead of '' in stuff
SELECT CONVERT(VARCHAR(10), GETDATE(), 101)+' '+STUFF(RIGHT(CONVERT(VARCHAR(26), GETDATE(), 109),14),9,4,' ')
output : 09/13/2012 11:15:59 PM