繁体   English   中英

将字符串转换为日期和时间

[英]convert string to both date and time

我有一个数据,其中日期和时间以yyyymmdd_time(20161012_1528)格式出现。

我想将它转换为SQL Server DB中的日期时间为2016-10-12 15:28:00:00

有没有直接的方法来做到这一点。还是要创建一个自定义函数?

Declare @String varchar(25) = '20161012_1528'

Select cast(left(@String,8)+' '+Stuff(right(@String,4),3,0,':') as datetime)

要么

Select cast(Stuff(Replace(@String,'_',' '),12,0,':') as datetime)

返回

2016-10-12 15:28:00.000

请尝试以下方法,它需要使用一些日期时间和转换功能

declare @dt datetime
declare @str varchar(40) = '20161012_1528'

select @dt = 
    DATEADD(MI, CAST(right(@str,2) as int), 
        DATEADD(hh, cast(SUBSTRING(@str,10,2) as int), 
            CONVERT(datetime, left(@str,8))
        )
    )
select @dt

我能找到的最接近的是日期时间格式112,它没有考虑“_hhmm”。 我强烈建议将转换放入T-SQL,因为优化器不能很好地处理UDF。

T-SQL看起来像:DECLARE @datetimestring nvarchar(max)='20161012_1528'

SELECT
    dateadd(
        minute,convert(
            int,substring(
                @datetimestring,charindex(
                    '_',@datetimestring
                )+3,2
            )
        ),dateadd(
            hour,convert(
                int,substring(
                    @datetimestring,charindex(
                        '_',@datetimestring
                    )+1,2
                )
            ),convert(
                datetime, substring(
                    @datetimestring,0,charindex(
                        '_',@datetimestring
                    )
                ), 112
            )
        )
    )

另一种选择是将字符串格式化为更短的预期日期格式。

SELECT
    convert(
        datetime,replace(
            stuff(
                stuff(
                    stuff(
                        @datetimestring,5,0,'-'
                    ),8,0,'-'
                ),14,0,':'
            ),'_',' '
        )
    )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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