Turn string with date and time to hh:mm - sql

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

Related

Is there a simpler method for getting the two digit year?

EDIT: Forced to use 2008 R2
I need to get the two digit year to appended to an invoice number (for simplicity sake I am using a test variable). Previously I only needed the month and day appended but the customer is now asking for the two digit year.
My Method: REPLACE + SUBSTRING + STR + YEAR(variable DATETIME)
REPLACE((SUBSTRING(STR (Year(#Date),4),3,2)), ' ', '0')**
My code:
DECLARE #TestVariable AS VARCHAR(100),
#Date as datetime = GetDate()
SET #TestVariable = '1234'
+ REPLACE(STR(MONTH(#Date), 2), ' ', '0')
+ REPLACE(STR(DAY(#Date), 2), ' ', '0')
+ REPLACE((SUBSTRING(STR (Year(#Date),4),3,2)), ' ', '0')
PRINT #TestVariable
Honestly, just don't work with 2 digit years any more; learn the lessons of last century's mistake and use 4 digits.
If you "have" to, then you could use CONVERT with a style code, and then just replace the characters with an empty string:
DECLARE #TestVariable varchar(100) = '1234',
#Date datetime = GETDATE();
SELECT #TestVariable + REPLACE(CONVERT(varchar(8),#Date, 1),'/','');
You can simplify the whole process, not just the year portion. Using FORMAT you can accomplish this easily.
DECLARE #TestVariable AS VARCHAR(100) = '1234'
, #Date as datetime = GetDate()
Select #TestVariable + FORMAT(#Date, 'MMddyy')
select replace(convert(varchar(20),#date,1)'/','') --or any other you need
See the docs
I'll echo others' sentiment of "do you really have to use a two-digit year"? But if you have to, I like this sort of thing
set #TestVariable = '1234'
+ right('0' + cast(month(#date) as varchar(2)), 2)
+ right('0' + cast(day(#date) as varchar(2)), 2)
+ right('0' + cast(year(#date) % 100 as varchar(2)), 2);
To talk through the general approach, I'm using right('0', «something», 2) as a means to zero pad to two places, using cast(«something» as varchar(2)) to get a string instead of a number (so implicit conversion doesn't just add zero and the relevant datepart), and finally year(#date) % 100 to get the last two digits of the date.

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

Converting separate columns for mm, dd, and yr into a workable mm/dd/year format

Basically I have 3 separate columns in a table. I will call them SMonth, Sday, Syear. They are stored as numeric values for some reason. I can use the following string to format them into what looks like a date but doesn't allow me to use functions such as sort, order by, datediff or dateadd.
CAST(SMonth AS varchar(2)) + '/' + CAST(SDay varchar(2)) + '/' + CAST(SYear AS varchar(4))
Anyone know how to convert this into a workable date, without changing the table?
It doesn't matter how it looks as long as I can use it ie a date or datetime makes no difference.
Thanks in advance.
Just convert your result into a date or datetime.
DECLARE #SMonth AS INT = 12
DECLARE #SDay AS INT = 31
DECLARE #SYear as INT = 2013
SELECT CONVERT(DATE,CAST(#SMonth AS varchar(2)) + '/' + CAST(#SDay AS varchar(2)) + '/' + CAST(#SYear AS varchar(4)))
you should convert format the string as yyyy/mm/dd in order to make sure that SQL Server uses ODBC canonical format
SELECT CONVERT(date, CONVERT(varchar, Syear) + '/' + convert(VARCHAR, SMonth) + '/' + convert(VARCHAR, SDay ) )
Otherwise it your results could depend on the default dateformat or someone changed it using SET DATEFORMAT, for example:
05/10/2013 could mean
May 10, 2013 if the DATEFORMAT is U.S.
October 5, 2013 if the DATEFORMAT is Brithish / French
see this for complete reference of dateformat

converting varchar to date format

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)

Convert CMMDDYY into date in SQL Server

If I have a date string in the format of CMMDDYY
C = 0, 1 or 2 where 0 represents 19, 1 represents 20 and 2 represents 21
Example:
1022511 would be 02/25/2011 in mm/dd/yyyy format.
Is there a way to convert this into mm/dd/yyyy format in sql server?
Is CMMDDYY even a valid date format? I haven't found much information on it.
The Year algorithm is simply: (19 + int(C))*100 + int(yy)
Try this:
declare #st nvarchar(7)
set #st = '1030609'
select
cast(
substring(#st,2,2) + '/'
+ substring(#st,4,2) + '/'
+ cast((19 + cast(substring(#st,1,1) as int) )* 100
+ cast(substring(#st,6,2) as int) as nvarchar)
as datetime)
This outputs:
It doesn't sound like a built in date format but you should be able to find it on msdn if it is. If not you could write a function in SQL server that parses a string in that format to a DateTime object