当分钟和秒是一位数字时,如何更改下面的代码以用 0 填充分钟和秒?
下面的代码正在做我想要它做的事情,将时间转换为适合我需要的格式。然而,当分钟和秒都是个位数时,格式看起来不太好。我想调整代码以在需要的地方填充分钟和秒。有什么建议吗?再次强调,我希望尽可能保留现有代码。
谢谢你!
SELECT SUBSTRING(CONVERT(CHAR(14), DateTimeRaw, 100), 13, 2) + ':' +
CONVERT(nvarchar, DATEPART(minute, DateTimeRaw)) + ':' +
CONVERT(nvarchar, DATEPART(second,
DateTimeRaw)) + '.' + CONVERT(nvarchar, DATEPART(ms, DateTimeRaw) / 100)
+ ' ' + CONVERT(nvarchar, CASE WHEN datepart(hour, DateTimeRaw)
< 12 THEN 'AM' ELSE 'PM' END) AS AGMPLUSMSTIME
FROM RAW
The code below is doing just what i want it to do, as far as converting the time to a format that works for my needs. However, when the minutes and seconds are in the single digit, the format is not looking good. I would like to adjust the code to pad the minutes and seconds where it is needed. Any suggestions? Again, i would like to stay with the existing code as much as possible.
Thank you!
SELECT SUBSTRING(CONVERT(CHAR(14), DateTimeRaw, 100), 13, 2) + ':' +
CONVERT(nvarchar, DATEPART(minute, DateTimeRaw)) + ':' +
CONVERT(nvarchar, DATEPART(second,
DateTimeRaw)) + '.' + CONVERT(nvarchar, DATEPART(ms, DateTimeRaw) / 100)
+ ' ' + CONVERT(nvarchar, CASE WHEN datepart(hour, DateTimeRaw)
< 12 THEN 'AM' ELSE 'PM' END) AS AGMPLUSMSTIME
FROM RAW
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样:
结果:
我使用 getdate() 而不是您的字段,仅作为示例
How about this:
Result:
I used getdate() instead of your field, just as an example
基本上:将 2 个零与您的时间值连接起来,最后得到诸如
001
、0023
或0059
之类的内容,然后取最右边的 2 个零字符,分别为01
、23
、59
。Basically: concatenate 2 zeroes with your time value, ending up with something like
001
,0023
, or0059
, then take the 2 right-most characters, leaving you with01
,23
,59
respectively.