简体   繁体   中英

How to cast varchar to datetime in sql

I need to cast a string to a datetime so i can compare it later.

The varchar that i have is like this format:

     29/11/2013 12:00:00 a.m.  

And i need it to cast to:

     2013-11-29 00:00:00.000

Im using MSSQL Server 2012

Thx for all

Please, have a look a CAST and CONVERT for more information.

Here are some examples:

-- converting from DD-MM-YYYY
select CONVERT(datetime, '29/11/2013 12:00:00 AM', 103)

-- converting from MM-DD-YYYY
select CONVERT(datetime, '11/29/2013 12:00:00 AM', 101)

IF Your date is of type varchar in the database then if you need to retrieve then these cases arises:: case1:if your data is in the format of "dd-MM-yyyy" then you need to use query as follows Query:: select * from [yourTableName] where convert(datetime,YourDateColumn,103) between '2016-02-12'(yyyy-MM-dd) AND '2016-03-12'

case2:if your data is in the format of "dd-MM-yyyy HH:mm:ss"

then you need to use query as follows Query:: select * from [yourTableName] where convert(datetime,YourDateColumn,105) between '2016-02-12'(yyyy-MM-dd) AND '2016-03-12'

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