问题描述
我在 SQL Server 2008 中有一个日期时间字段,它以军事格式(或国际格式,如果您愿意)存储日期和时间
I have a datetime field in SQL Server 2008 which stores the date and time in military format (or international format if you prefer)
示例:
2011-02-15 10:00:00.000
2011-02-15 15:30:00.000
2011-02-15 17:30:00.000
我需要以标准的美国时间格式检索其中的仅时间部分.
I need to retrieve the time only portion of this in standard U.S. time format.
所以
2011-02-15 10:00:00.000 needs to become 10:00 AM
2011-02-15 15:30:00.000 needs to become 3:30 PM
2011-02-15 17:30:00.000 needs to become 5:30 PM
我正在寻找在 T-SQL 中完成此任务的最佳方法.
I am looking for the best way to accomplish this in T-SQL please.
推荐答案
一种方法是:
转换为 varchar,这会给你:
Convert to varchar, which will give you:
Select CONVERT(varchar, @dt, 100) -- where @dt is your date time
2011 年 2 月 15 日下午 3:30
Feb 15 2011 3:30PM
随后,删除日期,并从右边获得 7 个字符,这是最多的,添加 TRIM 只是为了额外的安全,但可能不需要.
Subsequently, to remove the date, and get 7 chars from the right, which is the most, and TRIM is added just for extra safety, but probably isn't needed.
Select LTRIM(RIGHT(CONVERT(varchar, @dt, 100),7))
会给你 3:30PM
旁注:Denali 让这一切变得更简单,不再是神奇的数字
Side Note: Denali makes this easier, no more magic numbers
这篇关于使用军用时间的日期时间字段 - 仅在标准时间需要时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!