Thursday, December 16, 2010

SQL Server: Convert 24 hour format time into 12 hour format

Hi,
Here is an example of converting time data type i.e.13:09 which is in 24 hr format into 12 hr format i.e  1:09 format.

Create Function :


alter FUNCTION dbo.Split1(@String varchar(8000), @Delimiter char(1))    
returns @temptable TABLE (items varchar(8000))    
as    
begin    
declare @idx int    
declare @slice varchar(8000)
declare @count int
declare @finaltime varchar(5)
set @count=0  
  
select @idx = 1    
if len(@String)<1 or @String is null  return    
  
while @idx!= 0    
begin    
set @count=@count+1
set @idx = charindex(@Delimiter,@String)    
if @idx!=0    
set @slice = left(@String,@idx - 1)    
else    
set @slice = @String    

if((len(@slice)>0))
begin
declare @hrtime varchar(2)
set @hrtime=convert(varchar(2),@slice)
if(@count=1)
begin
declare @hrinttime int
set @hrinttime=convert(int,@hrtime)
if(@hrinttime>12)
begin
set @hrinttime=@hrtime-12
end
else
begin
set @hrinttime=@hrtime
end


--insert into @temptable(Items) values(@hrinttime)
set @finaltime =@hrinttime
set @finaltime=@finaltime+':'


end
else
-- insert into @temptable(Items) values(@hrtime)
set @finaltime=@finaltime+@hrtime
  -- insert into @temptable(Items) values(@slice)
end

set @String = right(@String,len(@String) - @idx)    
if len(@String) = 0 break    
end

insert into @temptable (Items) values(@finaltime)
return    
end




Run Function in this way:
select top 10 * from Split1('13:09',':')  

No comments:

Post a Comment