【问题标题】:How to convert an int to display as datetime?如何将 int 转换为显示为日期时间?
【发布时间】:2021-04-10 13:59:16
【问题描述】:

如何将下面的 int 转换为在 ssms 中显示为日期时间

'201061311912'

【问题讨论】:

  • 你想要什么日期时间?
  • 这种格式 mm/dd/yyyy hh:mm
  • 尝试计算:是 2010 年和 61 月吗?还是6131年??还是 61 年和时间 31:19:12? @GordonLinoff 你发现了丢失的 0

标签: sql tsql datetime sql-server-2012 ssms


【解决方案1】:

您可以使用datetimefromparts(),如果您的字符串格式为 YYYYMMDDHHMMSS:

select datetimefromparts(left(str, 4), substring(str, 5, 2), substring(str, 7, 2),
                         substring(str, 9, 2), substring(str, 11, 2), substring(str, 13, 2), 0)
from (values ('20100613011912')) as v(str);

这不完全是您问题中的格式,但它可能是您想要的。

【讨论】:

  • 如果你有很多行要在一个查询中执行此操作,我建议将 Linoff 的查询转换为函数。
  • 如何将它们转换成函数?
  • @Jason312 。 . .我用户定义的函数只会减慢速度。
【解决方案2】:

除非我遗漏了什么,否则不能这么简单吗?

select cast(format(20100613011912,'####-##-## ##:##:##') as datetime)

【讨论】:

    猜你喜欢
    • 2013-07-25
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 2019-03-07
    • 2012-04-30
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多