Reputation: 173
I wrote a function which converts a string into datetime. So,this is what I did
CREATE FUNCTION formatit(
@fromtime VARCHAR(50) -- varchar
)
RETURNS DATETIME
AS
BEGIN
DECLARE @from varchar(50)
DECLARE @value
IF (CHARINDEX('NOON',@fromtime,0)) = 0 THEN
SET @from = CONVERT(DATETIME, @fromtime)
ELSE
SET @from =CONVERT(DATETIME, '01/01/2000 12pm')
RETURN(@from)
END
SELECT dbo.formatit('04/12/2011 NOON ')
So, u can see that if fromtime consists of word NOON i'm trying to use a default date. But i've been getting a error 'Conversion failed when converting datetime from character string.'
It works fine when I enter any time like 4 pm etc. but fails when i give noon. can u please letme know the way i can handle this?
Upvotes: 0
Views: 1110
Reputation: 70538
this works
declare @from datetime
SET @from =CONVERT(DATETIME, '01/01/2000 12:00 pm')
The following was tested.
CREATE FUNCTION formatit(
@fromtime VARCHAR(50) -- varchar
)
RETURNS DATETIME
AS
BEGIN
DECLARE @from datetime
IF (CHARINDEX('NOON',@fromtime,0)) = 0
SET @from = CONVERT(DATETIME, @fromtime)
ELSE
SET @from =CONVERT(DATETIME, '01/01/2000 12pm')
RETURN(@from)
END
SELECT dbo.formatit('04/12/2011 NOON ')
Upvotes: 1
Reputation: 46067
I think you need to add the minutes after the 12, and put a space between the time and the AM/PM. See below:
SET @from = CONVERT(DATETIME, '01/01/2000 12:00 PM')
Upvotes: 1