Need to format char(4) hhmm to time only or text to look like hh:mm in sql - sql

In the script below, How do I convert the column HHMM to HH:MM and
convert it to 12hr clock?
The column is a char(4) and format 0000 - 2359.
Just want time or text with a colon(:), no date.
Please note that I do not want date or seconds. How do I do this?
Thank you for your help!
Select
th.[store] as 'My Store',
---> this column th.hhmm as Time, (I need this to format hh:mm)
emp.[First Name],
td.Type as [Total],
Count(*) as Qty,
Convert(varchar(50),SUM(Amount1),1) AS Amount

Try this. It uses LEFT and RIGHT functions
declare #time char(4)='2359'
select left(convert(varchar(100),cast(concat(left(#time,2),':',right(#time,2)) as time),9),5)+
' '+
right(convert(varchar(100),cast(concat(left(#time,2),':',right(#time,2)) as time),9),2)

SQL Server:
right('00' + cast((cast(substring(th.hhmm, 1, 2) as int) - 1) % 12 + 1 as varchar(2)), 2) +
':' + substring(th.hhmm, 3, 2) +
case when cast(substring(th.hhmm, 1, 2) as int) >= 12 then 'pm' else 'am' end

You can use substr to do this in Oracle.
select substr(th.hhmm,1,2)||':'||substr(th.hhmm,3,2) from t
In SQL Server, you can use substring
select substring(th.hhmm,1,2)+':'+substring(th.hhmm,3,2) from t
Fiddle with sample data
Edit:
select
case when cast(substring(th.hhmm,1,2) as int) < 12 then
case when cast(substring(th.hhmm,1,2) as int) = 0 then
'12'+':'+substring(th.hhmm,3,2)+' AM'
else substring(th.hhmm,1,2)+':'+substring(th.hhmm,3,2)+' AM' end
when cast(substring(th.hhmm,1,2) as int) > 12 then
cast(substring(th.hhmm,1,2)%12 as varchar(2)) +':'+substring(th.hhmm,3,2)+' PM'
when cast(substring(th.hhmm,1,2) as int) = 12 then
substring(th.hhmm,1,2)+':'+substring(th.hhmm,3,2)+' PM'
end

Related

DateTime to time interval in T-Sql

I am working on an SSRS report and I need to display hourly data count in a table.
The hourly interval need to be displayed as 4:00pm - 5:00pm
I have a log table which has DateTime available with each transaction. This table refreshes daily.
I am grouping on the hour component of this timestamp to get the hourly count.
Is there any option available in SQL/SSRS for converting hourly value to 04:00pm- 05:00pm format?
I would recommend that you simply create a simple scalar function in SQL Server for this one. See following example:
CREATE FUNCTION DateTimeToHourInterval
(
#currentDateTime DATETIME
)
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE #nextHourDateTime DATETIME = DATEADD(HOUR, 1, #currentDateTime);
DECLARE #intervalStart VARCHAR(10) = REPLACE(REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(50), DATEADD(MINUTE, -1* DATEPART(MINUTE, #currentDateTime), #currentDateTime), 100), 7)), 'PM', ' PM'), 'AM', ' AM');
DECLARE #intervalEnd VARCHAR(10) = REPLACE(REPLACE(LTRIM(RIGHT(CONVERT(VARCHAR(50), DATEADD(MINUTE, -1* DATEPART(MINUTE, #nextHourDateTime), #nextHourDateTime), 100), 7)), 'PM', ' PM'), 'AM', ' AM');
RETURN #intervalStart + ' - ' + #intervalEnd
END
The function can now be used as follow:
SELECT dbo.DateTimeToHourInterval(GETDATE());
Use case statement:
SELECT CASE
WHEN DATEPART(hour,TransactionDateTime) = 0 THEN '12:00am-01:00am'
WHEN DATEPART(hour,TransactionDateTime) = 1 THEN '01:00am-02:00am' ...
END FROM your_table
Dynamic way:
SELECT CASE
WHEN DATEPART(hour,TransactionDateTime) >12 THEN cast (DATEPART(hour,TransactionDateTime) -12 as VARCHAR (2)) + ':00pm-' +cast(DATEPART(hour,TransactionDateTime) -11 as VARCHAR (2)) + ':00pm'
WHEN DATEPART(hour,TransactionDateTime) <12
cast (DATEPART(hour,TransactionDateTime) as VARCHAR (2)) + ':00am-' +cast(DATEPART(hour,TransactionDateTime)+1 as VARCHAR (2)) + ':00am'
WHEN DATEPART(hour,TransactionDateTime) =12
cast (DATEPART(hour,TransactionDateTime) as VARCHAR (2)) +':00pm-1:00pm'
END
FROM your_table
For corner case (11pm) handle am/pm using a nested case statement. check the datepart and return am/pm based on the results. I was not able to test the query since I am posting this from my smartphone.
Hope this helps
Use the below script to convert datetime to 12 hour format.
SELECT LEFT (STUFF(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,YourColumn,100),7)),7),6,0,''),2)+':00'+RIGHT (LTRIM(RIGHT(CONVERT(VARCHAR(20), YourColumn, 100), 7)),2)
+' - '+LEFT (STUFF(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar, DATEADD(hh, 1, YourColumn),100),7)),7),6,0,''),2)+':00'+RIGHT (LTRIM(RIGHT(CONVERT(VARCHAR(20), DATEADD(hh, 1, YourColumn), 100), 7)),2)
FROM YourTable
Sample output :

Convert string to Datetime

I've received a flat file and after parsing and inserting it in a table. I've a column which has dates in a format yyyyMMddhhmmss
Here, yyyy is year, MM is month, dd is day, hh is hours, mm is minute and ss is seconds part
I'm trying to convert this to DateTime type as mentioned below but not working for me
SELECT CAST(StrDate as DateTime) FROM [dbo].[Mytable]
For example:
Column has a value 20150121190941 in Varchar format and it should be converted to DateTime as 2015-01-21 19:09:41.000
I apologize if it's a duplicate one.
You can use select DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
declare #dt nvarchar(25) = '20150121190941'
select datetimefromparts(left(#dt,4), substring(#dt,5,2), substring(#dt,7,2),substring(#dt,9,2), substring(#dt,11,2), substring(#dt,13,2), '000')
SQL Server readily recognizes YYYYMMDD as a date. So, converting the first 8 characters to a date is easy. Alas, I don't think there is a time representation without colons.
So, here is one rather brutal method:
select (convert(datetime, left(StrDate, 8)) +
convert(time, substring(StrDate, 9, 2 ) + ':' + substring(StrDate, 11, 2 ) + ':' + substring(StrDate, 13, 2 )
)
)
Declare #dt varchar(50)
set #dt=20150121190941
create table tblDateTbl
(
col1 datetime
)
insert into dt (col1)
select SUBSTRING(#dt,1,4) + '-' + SUBSTRING(#dt,5,2) + '-' + SUBSTRING(#dt,7,2)+ ' ' + SUBSTRING(#dt,9,2)+ ':' + SUBSTRING(#dt,11,2)+ ':' + SUBSTRING(#dt,13,2)+ '.000'

SQL conversion from varchar to datetime

One of the columns of my SQL Server table is mm:ss of varchar type where mm = minutes and ss = seconds.
I need to get the average of that column.
Should I convert that column to datetime format first? If so can you tell me how? If not can you tell me what I should do?
Here is my failed attempt to convert it to datetime :
SELECT CONVERT(DATETIME, '2014-01-01 '+Pace+':00', 108)
Where pace is a varchar like 23:05
If you want the average, I would convert the column to number of seconds and work with that:
select avg(pace_secs) as average_in_seconds
from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs
from t
) t;
If you want this back in the format, then you can do:
select right('00' + cast(avg(pace_secs) / 60 as int), 2) + ':' +
right('00' + avg(page_secs) % 60), 2)
from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs
from t
) t;
declare #pace varchar(20) = '23:05 ';
SELECT cast( '2014-01-01 '+cast(#pace as varchar(5))+':00' as datetime)
For SQL2012 and later
SELECT
FORMAT(DATEADD(second,AVG(DATEDIFF(second,0,'00:'+[Pace])),0),'mm:ss')
FROM MyTable

CAST Correct VARCHAR to DateTime

Good Day
I am working of a existing SQL Server Database. What the developers did is to keep the Date and time separate. The Date is in DateTime format (what I want) but the time is incorrect. if it is 14:30 it shows as 1430 when its 09:25 shows as 925. I am trying tyo combine the date and time to have a Date Time view for an program I am writing on top of this database.
I have created the date as a normal date like this:
CASE
WHEN LEN(T0.BeginTime) = 3 THEN '0' + LEFT(T0.BeginTime, 1) + ':' + RIGHT(T0.BeginTime, 2)
ELSE LEFT(T0.BeginTime, 2) + ':' + RIGHT(T0.BeginTime, 2)
END AS 'NEW Start Time'`
The date now looks like it's the correct format but when I want to combine the date and time I get VARCHAR to DateTime error.
How can I fix this?
This is the error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value (ONLY RAN 804 RECORDS)
Thanks
This should do the trick, Hope it helps.
DECLARE #DateTime TABLE (
DateWithTime DATE,
BeginTime INT);
INSERT INTO #DateTime
VALUES ('2014-08-04', '1525'),
('2014-08-04', '525'),
('2014-08-04', '15'),
('2014-08-04', '5'),
('2014-08-04', '0'),
('2014-08-04', '90')
;WITH cte_BeginTimeFix
AS (
SELECT
CONVERT(VARCHAR(10), DateWithTime, 120) AS DateWithTime,
RIGHT('0000' + CAST(BeginTime AS VARCHAR(4)), 4) AS BeginTime
FROM #DateTime
)
, cte_DateString
AS (
SELECT DateWithTime,
BeginTime,
DateWithTime + ' ' + STUFF(STUFF('00:00:00.000', 4, 2, RIGHT(BeginTime, 2)), 1, 2, LEFT(BeginTime, 2)) AS DateTimeStr
FROM cte_BeginTimeFix
)
SELECT DateWithTime,
BeginTime,
CASE
WHEN ISDATE(DateTimeStr) = 1 THEN CAST(DateTimeStr AS DATETIME)
ELSE NULL
END AS DateTimeStr
FROM cte_DateString
A different approach is to convert the time column in minutes and add it to the date
DATEADD(minute, T0.BeginTime / 100 * 60 + T0.BeginTime % 100
, CONVERT(VARCHAR, T0.BeginDate, 112))
with that the length of the time column doesn't matter
This should work:
CONVERT
(
DATETIME,
CONVERT(VARCHAR,T0.Date,112) +
' ' +
CASE
WHEN ISNULL(T0.BeginTime,'0') = '0'
THEN '00:00'
ELSE
RIGHT
(
'00' + LEFT(T0.BeginTime,LEN(T0.BeginTime) - 3),
2
) +
':' +
RIGHT(T0.BeginTime,2)
END
)

Get Hours and Minutes (HH:MM) from date

I want to get only hh:mm from date.
How I can get this?
I have tried this :
CONVERT(VARCHAR(8), getdate(), 108)
Just use the first 5 characters...?
SELECT CONVERT(VARCHAR(5),getdate(),108)
You can easily use Format() function instead of all the casting for sql 2012 and above only
SELECT FORMAT(GETDATE(),'hh:mm')
This is by far the best way to do the required conversion.
Another method using DATEPART built-in function:
SELECT cast(DATEPART(hour, GETDATE()) as varchar) + ':' + cast(DATEPART(minute, GETDATE()) as varchar)
If you want to display 24 hours format use:
SELECT FORMAT(GETDATE(),'HH:mm')
and to display 12 hours format use:
SELECT FORMAT(GETDATE(),'hh:mm')
Following code shows current hour and minutes in 'Hour:Minutes' column for us.
SELECT CONVERT(VARCHAR(5), GETDATE(), 108) +
(CASE WHEN DATEPART(HOUR, GETDATE()) > 12 THEN ' PM'
ELSE ' AM'
END) 'Hour:Minutes'
or
SELECT Format(GETDATE(), 'hh:mm') +
(CASE WHEN DATEPART(HOUR, GETDATE()) > 12 THEN ' PM'
ELSE ' AM'
END) 'Hour:Minutes'
The following works on 2008R2+ to produce 'HH:MM':
select
case
when len(replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')) = 4
then '0'+ replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')
else replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','') end as [Time]
You can cast datetime to time
select CAST(GETDATE() as time)
If you want a hh:mm format
select cast(CAST(GETDATE() as time) as varchar(5))
Here is syntax for showing hours and minutes for a field coming out of a SELECT statement. In this example, the SQL field is named "UpdatedOnAt" and is a DateTime. Tested with MS SQL 2014.
SELECT Format(UpdatedOnAt ,'hh:mm') as UpdatedOnAt from MyTable
I like the format that shows the day of the week as a 3-letter abbreviation, and includes the seconds:
SELECT Format(UpdatedOnAt ,'ddd hh:mm:ss') as UpdatedOnAt from MyTable
The "as UpdatedOnAt" suffix is optional. It gives you a column heading equal tot he field you were selecting to begin with.
TO_CHAR(SYSDATE, 'HH')
I used this to get the current hour in apex PL/SQL