Construct DateTime using today's date at a specific time

爷,独闯天下 提交于 2019-12-18 13:20:13

问题


I'd like to get 4:30 PM of the current day. Hard-coding this way doesn't work:

SELECT '07242012 16:30:00.000'

This is proving to be more difficult than I thought it would be. How do I approach this?


回答1:


SQL Server 2000 / 2005:

SELECT DATEADD(MINUTE, 30, DATEADD(HOUR, 16, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP)));

-- or

SELECT DATEADD(MINUTE, (16*60) + 30, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP))

-- or

SELECT CONVERT(DATETIME, CONVERT(CHAR(9), CURRENT_TIMESTAMP, 112) + '16:30');

SQL Server 2008+:

SELECT CONVERT(DATETIME, CONVERT(DATE, CURRENT_TIMESTAMP)) + '16:30';

SQL Server 2012:

SELECT SMALLDATETIMEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), DAY(GETDATE()), 16, 30);



回答2:


Probably the easiest thing to do is to cast the current date/time to a date (stripping the time off), cast it back to a datetime to allow use of datetime's overloaded + (plus) and, finally cast your desired textual time to a datetime. As follows:

select cast(cast(sysutcdatetime() as date) as datetime) + cast('16:30' as datetime)

returns (when run on 11th Jan 2018):

2018-01-11 16:30:00.000



回答3:


You can construct this as you like with day, hour, minute etc.

SELECT CURDATE() - interval 1 DAY + interval 2 



回答4:


 select(dateadd(day, datediff(day, 0, getdate()), 0) + '20:00') as specified_date

specified_date - Output Column name

20:00 - Specified time(24 hr Format -Default)

getdate() - To get Today's date.



来源:https://stackoverflow.com/questions/11635428/construct-datetime-using-todays-date-at-a-specific-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!