开发者

How to convert different strings to date time

开发者 https://www.devze.com 2023-04-10 20:24 出处:网络
I have a table in SQL Server 2008 that stores date/time values as varchar(max) (don\'t ask). I\'ve been tasked with converting these values from PST to GMT. The values are in one of two formats in eac

I have a table in SQL Server 2008 that stores date/time values as varchar(max) (don't ask). I've been tasked with converting these values from PST to GMT. The values are in one of two formats in each row:

Mar 12 2009 4:00PM

OR

3/12/2009 4:00:00PM

How can I, using T-SQL, determine which format the date is in (I'm thinking maybe check to see if it starts with a character or a numeric value) then convert that to a SQL datetime variable so that I can use DATEADD to add hours to it?

I've already written the T-SQL to create a cursor and loop through the rows, I'm just not sure how to detect which format it's in and then convert to DATETIME. I'm sure could probably hack it, but I figured the folks here at开发者_如何学C SO could provide me with a CORRECT way to do it.


you can use the convert function which will work for both the scenarios

 SELECT convert(datetime, '3/12/2009 4:00:00PM') -- 2009-03-12 16:00:00.000

 SELECT convert(datetime, 'Mar 12 2009 4:00PM')  -- 2009-03-12 16:00:00.000

then you can format it as you like


This works fine for me, no looping or cursors required:

DECLARE @Date varchar(MAX)

SET @Date = 'Mar 12 2009 4:00PM'

SELECT DATEADD(hh,8,CONVERT(DATETIME,@date))

SET @Date ='3/12/2009 4:00:00PM'

SELECT DATEADD(hh,8,CONVERT(DATETIME,@date))
0

精彩评论

暂无评论...
验证码 换一张
取 消