简体   繁体   中英

String to DateTime SQL Conversion

I know this has been asked several times but I haven't seen it asked for my particular situation.

If a text was in this format: Dec 30 2006 12:38AM Is there any way to convert this to an actual datetime. I am not excited about creating a function to parse this to a date using substrings, etc.

A previous developer developed the whole application and decided to store all the date values in the database as a VARCHAR which conveniently changed them from something like: 2016-12-30 00:38:00 to Dec 30 2006 12:38AM . This makes them non comareable (SMH)

Just use cast() :

select cast('Dec 30 2006 12:38AM' as datetime)

Here is a SQL Fiddle.

--Please try this

declare @var varchar(30) = 'Dec 30 2006 12:38AM' select convert(datetime, @var)

Since you are converting strings (which is always risky), I would suggest try_convert() if 2012+. Try_Convert() will return a null if the conversion fails rather than throwing an error.

Example

Select ValidDate = try_convert(datetime,'Dec 30 2006 12:38AM')
      ,BogusDate = try_convert(datetime,'Not a Valid Date String')

Returns

ValidDate                BogusDate
2006-12-30 00:38:00.000  NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM