gpt4 book ai didi

sql - 如何将日期时间转换为时间

转载 作者:行者123 更新时间:2023-12-02 03:27:35 25 4
gpt4 key购买 nike

我正在使用 CAST 语法将 DateTime 字段转换为时间。

select CAST([time] as time) as [CSTTime]

日期时间2015-03-19 00:00:00.000

当前输出:时间03:05:36.0000000

我只需要 HH:MM:SS 而不是毫秒或 0000

如何过滤或将其转换为精确的 HH:MM:SS 格式。

最佳答案

时间未以其显示格式存储在 SQL Server 中。
因此,从用户的角度来看,你可以说它没有格式。
当然,这并不完全准确,因为它确实有存储格式,但作为普通用户,您无法真正使用它。
对于所有日期和时间数据类型都是如此:
DateDateTimeOffsetDateTime2SmallDateTimeDateTimeTime.

如果您需要一种格式,那么您不需要转换为时间,而是转换为char。使用Convert获取您需要的char:

SELECT CONVERT(char(10), [time], 108) as CSTTime 

如果您有兴趣,这里有一些背景数据:

this article作者于 2000 年出版,深入解释了 SQL Server 如何处理日期和时间。我怀疑 2000 年到 2015 年间 SQL Server 在内部存储 datetimedatetime 值的方式是否发生了重大变化。

如果您不想阅读全部内容,这里是相关引用:

So how does SQL Server internally store the dates? It uses 8 bytes to store a datetime value—the first 4 for the date and the second 4 for the time. SQL Server can interpret both sets of 4 bytes as integers.
........
........
SQL Server stores the second integer for the time as the number of clock ticks after midnight. A second contains 300 ticks, so a tick equals 3.3 milliseconds (ms).

由于 time 实际上存储为 4 字节整数,因此它实际上没有作为数据类型的组成部分的格式。

您可能还想查看this article有关代码示例的更详细说明。

关于sql - 如何将日期时间转换为时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30032915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com