简体   繁体   English

获取今天午夜的日期和时间并添加到它

[英]get the date and time for today at midnight and add to it

是否有一个sql命令可以在午夜获取今天的日期,并且能够为它添加几分钟的时间?

Date now midnight time: 现在是午夜时间:

Select DATEADD(d,0,DATEDIFF(d,0,GETDATE()))

ADD 600 Minutes: 增加600分钟:

Select DATEADD(mi,600,DATEDIFF(d,0,GETDATE()))

Yes, just use datediff and dateadd functions to strip the time from any date, then add a fractional portion of a day to that number 是的,只需使用datediff和dateadd函数从任何日期剥离时间,然后将一天的小数部分添加到该数字

Declare @aDate DateTime
Set @aDate = getDate()
Declare @Minutes Integer
Set @minutes = 600 -- 10 hours

Select DateAdd(day, DateDiff(day, 0, @aDate), 0) + @minutes / 1440.0  -- 1440 min/day
 -- or You could also use the dateadd again...
Select DateAdd(minute, @minutes , DateAdd(day, DateDiff(day, 0, @aDate), 0))

Both selects return 10:00 am on the same day (more or less). 两者都选择在同一天上午10:00(或多或少)返回。 This works because of, well, check out this SO answer 这是有效的,因为,检查这个SO答案

EDIT: Added sample script to show how this works: 编辑:添加示例脚本以显示其工作原理:

declare @dtTim datetime = getDate()
declare @today datetime = dateAdd(day, dateDiff(day, 0, @dtTim ), 0)
select  @dtTim, @today

You can also cast to date to strip off the time portion: 您还可以投射到date以剥离时间部分:

declare @minutes int = 600
declare @start datetime = cast(getdate() as date)
declare @finish datetime = dateadd(mi, @minutes, @start)

Although, honestly, I have no idea how it performs compared to 虽然,老实说,我不知道它的表现如何

dateadd(day, datediff(day, 0, getdate()), 0)

Use following: 使用以下:

select DATEADD(SECOND, 36000, CAST(CONVERT(VARCHAR(10), GETDATE(), 101) AS datetime))

This way you can adjust the seconds to pinpoint any time of day you want. 这样,您可以调整秒数以精确定位您想要的任何时间。

Please refer to this for date/time formatting in SQL Server: SQL Server Date/Time Formatting 请参阅此处了解SQL Server中的日期/时间格式SQL Server日期/时间格式

I had to do something similar, create a procedure to run from a certain time the previous day to a certain time on the current day This is what I did to set the start date to 16:30 on the previous day, basically subtract the parts you don't want to get them back to 0 then add the value that you want it to be. 我必须做类似的事情,创建一个程序,从前一天的某个时间运行到当天的某个时间这是我做的将开始日期设置为前一天的16:30,基本上减去了部分你不想让他们回到0然后添加你想要的值。

-- Set Start Date to previous day and set start time to 16:30.00.000

SET @StartDate = GetDate()
SET @StartDate = DateAdd(dd,- 1, @StartDate) 
SET @StartDate = DateAdd(hh,- (DatePart(hh,@StartDate))+16, @StartDate) 
SET @StartDate = DateAdd(mi,- (DatePart(mi,@StartDate))+30, @StartDate) 
SET @StartDate = DateAdd(ss,- (DatePart(ss,@StartDate)), @StartDate) 
SET @StartDate = DateAdd(ms,- (DatePart(ms,@StartDate)), @StartDate) 

Hope this helps someone. 希望这有助于某人。

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

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