简体   繁体   English

如何从日期时间格式的字段中显示AM或PM的时间?

[英]How do i show just the time with AM or PM from a field that is a datetime format?

I have a column of data in SQL that is currently in the datetime format. 我在SQL中有一列数据,当前采用日期时间格式。 It can be changed if needed. 如果需要,可以更改它。 I need to show just the time of day, to the 10th of a second, with either AM or PM attached also. 我需要只显示一天中的时间,到十分之一秒,同时连接AM或PM。 I do not want the date to be shown in this instance. 我不希望在这个例子中显示日期。

So instead of '1900-01-01 11:45:59.800' as an example, i need '11:45:59.8 AM'. 因此,作为一个例子,我需要'11:45:59.8 AM'而不是'1900-01-01 11:45:59.800'。
Also, this is not a current "getdate" time. 此外,这不是当前的“getdate”时间。 It is from a field of data i have called 'Time' I see all sorts of convert formats on the web, but none will pull this up for me. 它来自我称之为“时间”的数据领域,我在网上看到了各种各样的转换格式,但没有人会为我提供这些。

Thank you!!!! 谢谢!!!!

As in my comment, I'd advise you to not do this. 在我的评论中,我建议你不要这样做。

SQL Server is a place for data, and converting the data for display purposes is often a blurring of the lines that can come back to haunt you. SQL Server是一个数据存储的地方,为了显示目的而转换数据通常会模糊可能会让您困扰的线条。 (One example; what if you need that time as a Time somewhere else in the future. Are you going to convert it back from a string again?) (一个例子;如果你将来的那个时间作为一个时间在未来的其他地方怎么办。你要再从一个字符串转换回来吗?)

If it is Necessary, then you have to do some of the formatting yourself. 如果它是必要的,那么你必须自己做一些格式化。

SELECT
  RIGHT(CONVERT(VARCHAR(26), GETDATE(), 109), 14)

Or, more messy... 或者,更麻烦......

SELECT
  DATEPART(HOUR, GETDATE()) + ':' +
  DATEPART(MINUTE, GETDATE()) + ':' +
  DATEPART(SECOND, GETDATE()) + '.' +
  DATEPART(MILLISECOND, GETDATE()) +
  CASE WHEN DATEPART(HOUR, GETDATE()) < 12 THEN 'AM' ELSE 'PM' END


Did I say? 我说了吗? You're better doing it on the client side ;) 你最好在客户端做这件事;)

Rename your table field, Time is a reserved word and it will be a pain to maintain. 重命名您的表字段, Time是一个保留字,维护是一件痛苦的事。 Make sure you are using the new datetime2 data type if you want millisecond accuracy. 如果您想要毫秒精度,请确保使用新的datetime2数据类型。

To format the time part use: 要格式化时间部分使用:

SELECT CONVERT(TIME, [Time]) FROM [Your Table]

If you only want a three digits after the period you can use: 如果您只想在这段时间后使用三位数,您可以使用:

SELECT CONVERT(TIME(3), [Time]) FROM [Your Table] 

I think this will work if you want to get in HH:MM format 我想如果您想要使用HH:MM格式,这将有效

SELECT
  RIGHT(CONVERT(VARCHAR(26), GETDATE(), 117), 14)

You can also refer to this page for more formats 您还可以参考此页面以获取更多格式

http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc36271.1570/html/blocks/X41864.htm http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc36271.1570/html/blocks/X41864.htm

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

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