December 2, 2008 at 3:42 pm
Converting varchar to datetime T-SQL.
Hi, experts
How do I convert a varchar hhmm into a datetime 13:30:00 if the varchar hhmm = 1330?
Thank you.
December 2, 2008 at 7:40 pm
That's not really a DateTime datatype you asked for or it would have a date with it like this...
DECLARE @Time CHAR(4)
SET @Time = '1330'
SELECT CAST(STUFF(@Time,3,0,':') AS DATETIME)
If you're just trying to display it differently (best to do formatting in the GUI, if you have one), then this would work...
DECLARE @Time CHAR(4)
SET @Time = '1330'
SELECT STUFF(@Time,3,0,':') + ':00'
--Jeff Moden
Change is inevitable... Change for the better is not.
December 3, 2008 at 2:25 am
If times are AM, use
STUFF(REPLACE(STR(Col1, 4), ' ', '0'), 3, 0, ':')
N 56°04'39.16"
E 12°55'05.25"
December 3, 2008 at 2:41 am
pickgoods (12/2/2008)
Converting varchar to datetime T-SQL.Hi, experts
How do I convert a varchar hhmm into a datetime 13:30:00 if the varchar hhmm = 1330?
Thank you.
Jeff's answer will work only if you guarantee that you'll have 4 digits regardless of the value. For example if the time should be 9:05 will you varchar show 0905?
Adi
--------------------------------------------------------------
To know how to ask questions and increase the chances of getting asnwers:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
For better answers on performance questions, click on the following...
http://www.sqlservercentral.com/articles/SQLServerCentral/66909/
December 3, 2008 at 3:07 am
declare @nvsDateTime NVARCHAR(20)
set @nvsDateTime = '1330'
select REVERSE(SUBSTRING(REVERSE(@nvsDateTime),0,3) + ':' + SUBSTRING(REVERSE(@nvsDateTime),3,LEN(REVERSE(@nvsDateTime))))
try this.....
December 3, 2008 at 3:09 am
Which is easier than STUFF(REPLACE(STR(Col1, 4), ' ', '0'), 3, 0, ':')
N 56°04'39.16"
E 12°55'05.25"
December 3, 2008 at 2:21 pm
Thank you all of you.
They are very helpful. Especially this one: STUFF(REPLACE(STR('1416', 4), ' ', '0'), 3, 0, ':')
July 21, 2009 at 2:41 am
Thanks for enlightening me on the use of reverse and substring. Is a flexible way of manipulating string formats into numbers. cheers
July 21, 2009 at 6:28 am
Chethan Srinivas Shetty (7/21/2009)
Thanks for enlightening me on the use of reverse and substring. Is a flexible way of manipulating string formats into numbers. cheers
Just be careful, Chethan... REVERSE is a fairly expensive function and doing something like using 4 reverses in a function can really cause a bit of a drag on the CPU if you have to process a lot of rows. Correctly STUFFing a string like Peso did is much quicker.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply