【问题标题】:Convert from string(yyyyMMddHHmmss) to DateTime with SQL Server [duplicate]使用 SQL Server 从字符串(yyyyMMddHHmmss)转换为 DateTime [重复]
【发布时间】:2017-11-16 05:54:12
【问题描述】:

我正在从 Oracle 的 to_date 函数迁移到 SQL Server 的 convert 函数。

我想知道将yyyyMMddHHmmss格式的字符串转换为DateTime类型的好方法。

我可以写一个程序,但是太多余了,所以我想知道如何改进它。

'Get String Date (yyyyMMddHHmmss)
Dim strNowDate = Strings.Format(Now, "yyyyMMddHHmmss") 'format cannot be changed. (Because, referenced from many)

'some logics...

'Oracle script before migration.
sqlBuf.Append(" ,to_date('" & strNowDate & "', 'YYYYMMDDHH24MISS')" & vbCrLf)

'SQL Server script after migration.(too redundancy... I want to make it more cool.)
sqlBuf.Append(" ,convert(DATETIME, '" & DateTime.ParseExact(strNowDate, "yyyyMMddHHmmss", Globalization.DateTimeFormatInfo.InvariantInfo).ToString("yyyy-MM-dd HH:mm:ss") & "')" & vbCrLf)

【问题讨论】:

  • 试试convert(datetime, substring(@d,1,4) + '-' + substring(@d,5,2) + '-' + substring(@d,7,2) + ' ' + substring(@d,9,2) + ':' + substring(@d,11,2) + ':' + substring(@d,13,2))
  • 或者作为变体你可以使用STUFF-function SELECT CONVERT(datetime,STUFF(STUFF(STUFF(STUFF(STUFF('20171116115733',5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':'),120) -- yyyy-mm-dd hh:mm:ss
  • @T.Yanchi - 编辑在我的帖子中添加了隐形符号。你可以看到'?如果您执行以下操作SELECT 'CONVERT(datetime,STUFF(STUFF(STUFF(STUFF(STUFF(''201711161157‌​33'',5,0,''-''),8,0,''-''‌​),11,0,'' ''),14,0,'':''),17,0,'':''),120)'

标签: .net sql-server vb.net oracle


【解决方案1】:

ORACLE 和 SQL Server 都不同,我假设它的 SQL Server。 试试这个

select
convert(datetime,stuff(stuff(stuff('20171116115733', 9, 0, ' '), 12, 0, ':'),
        15, 0, ':')) ConvertedDate

这里给出了很多可能的方法

https://rdineshkumar.wordpress.com/tag/how-to-convert-yyyymmddhhmmss-to-datetimedatetime-in-sql-server/

【讨论】:

    【解决方案2】:

    这是我评论的变种

    SELECT CONVERT(datetime,STUFF(STUFF(STUFF(STUFF(STUFF('20171116115733',5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':'),120) -- yyyy-mm-dd hh:mm:ss
    

    【讨论】:

      猜你喜欢
      • 2014-01-15
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2013-02-26
      相关资源
      最近更新 更多