如何将日期时间转换为时间格式

时间:2014-12-08 15:14:08

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

我有一个在sql中返回datetime格式的查询:

SELECT time_in  
FROM job_punch_card  
WHERE emp_key=47 and punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)

这会返回2014-2-15 07:36:32.000之类的结果,但我只想要时间部分,而不是日期。我可以从SQL Server获取当前时间,如:

SELECT CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond

但我无法将此应用于我自己的查询。如何从上面的time_in表中仅检索时间?

4 个答案:

答案 0 :(得分:2)

在输出列上使用相同的CONVERT函数:

SELECT CONVERT(VARCHAR(8), time_in, 108) AS time_in  
FROM job_punch_card  
WHERE emp_key=47 and punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)

答案 1 :(得分:1)

如果您需要CAST类型,请使用TIME。如果你必须对结果集进行任何计算,这将使事情变得更容易。

SELECT CAST(time_in AS TIME(0)) AS time_in
FROM job_punch_card
etc., etc.

答案 2 :(得分:0)

几乎完全相同的方式:

SELECT CONVERT(VARCHAR(8), time_in, 108)
FROM job_punch_card  
WHERE 
    emp_key=47 and 
    punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)

答案 3 :(得分:0)

尝试:

SELECT CONVERT(VARCHAR(8),time_in,108) AS time_in_time_only
FROM job_punch_card  
WHERE emp_key=47 
    and punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)

或者:

SELECT CAST(time_in AS TIME) AS time_in_time_only
FROM job_punch_card  
WHERE emp_key=47 
    and punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)

后者的优点是时间数据类型而不是字符串,这对你正在做的事情很重要。