【发布时间】:2020-05-19 11:55:03
【问题描述】:
我有一个格式为
的日期(实际上是一个字符串)DD-MM-YYYY 00:00:00
我想要它的日期部分(我不在乎什么格式,我只需要它成为一个日期类型) 什么是最有效的方法?
【问题讨论】:
我有一个格式为
的日期(实际上是一个字符串)DD-MM-YYYY 00:00:00
我想要它的日期部分(我不在乎什么格式,我只需要它成为一个日期类型) 什么是最有效的方法?
【问题讨论】:
猜猜这就是诀窍:选择
convert(date,left(enddate, charindex(' ',enddate)),103)
【讨论】:
DECLARE @DTString varchar(20) = '19-05-2020 09:30:00'
SET @DTString = CONVERT(varchar(10), @DTString) -- Get Datepart (DD-MM-YYYY)
-- There is no implicit conversion from astring to date.
-- CONVERT won't work in that format. We need it in MM=DD-YYYY format.
DECLARE @Day varchar(02)
DECLARE @Month varchar(02)
SET @Day = LEFT(@DTString, 2) -- Get the Day
SET @Month = SUBSTRING(@DTString, 4, 2) -- Get the Month
-- STUFF(String to be modified , start position , number of chars to deleted , String to insert)
SET @DTString = STUFF(@DTString , 1 , 2 , @Month) -- Insert the Month at position 1, deleting 2 (the day )
SET @DTString = STUFF(@DTString , 4 , 2 , @Day ) -- Insert the Day at position 4, deleting 2 (the month)
SELECT @DTString -- Here the transformation from DD-MM-YYYY to MM-DD-YYYY
SELECT CONVERT(date, @DTString) -- Now we can convert
【讨论】: