Click here to Skip to main content
15,917,795 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have string in following format : 8.00p.m - 10.00p.m

now i want string in 8-10 PM format in sql

What I have tried:

SQL
select (SUBSTRING('8.00p.m',0,CHARINDEX('.','8.00p.m',0)))+ '-' +(SUBSTRING('10.00p.m',0,CHARINDEX('.','10.00p.m',-2)))
Posted
Updated 31-May-16 21:48pm
v2
Comments
Abhipal Singh 1-Jun-16 3:21am    
What if its 8:00a.m - 10:00p.m?
how do you want to handle this situation in your intended format?

To be honest, you're probably storing it wrong if you need to do that.
Storing data as NVARCHAR is simple, and easy for your app code, but it's a PITA to work with when you want to do anything with it, as you are string to see.
Instead, I'd store it as two non-string columns, a "start" and an "end" time column. The column content would depend on what I wanted to do with the data, and what it's for, but the simplest solution is to store it as an integer: "hours since midnight". Then your formatting it for your string becomes pretty simple: I'd write an SQL function that accepts an integer, and returns the time string:
SQL
CREATE FUNCTION [dbo].[HourToString] 
(
	-- Add the parameters for the function here
	@Hour INT
)
RETURNS NVARCHAR(4)
AS
BEGIN
    RETURN CASE WHEN @Hour = 0 THEN '12AM'
	       WHEN @Hour < 12 THEN CONVERT(NVARCHAR(4), @Hour) + 'AM'
		   WHEN @Hour = 12 THEN '12PM'
	       ELSE CONVERT(NVARCHAR(4), @Hour - 12) + 'PM'
		   END 
END
And everything else gets easier to work with later as well. Such as checking if you are in that time period, and so on!
 
Share this answer
 
Comments
Member 11466758 2-Jun-16 6:04am    
I am getting this string(2.00p.m - 4.00p.m) as slot in response i have to convert this string in above(2-4p.m) format in sql
Please, read MSDN documentation[^]. There you'll find everything what you want.

SQL
DECLARE @myDate DATETIME = GETDATE()
SELECT LEFT(CONVERT(VARCHAR(20), @myDate, 114), 5) AS MyCustomTimeFormat
--returns:
--09:47
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900