Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Update DATETIME Minutes and Seconds

I've been staring at this for quite a while and can't figure out how to go about doing it. I don't really have any code to post because I haven't even gotten close to figuring it out yet and everything I come up with just doesn't make any sense.

Anyways, we have an application that collects data every 5 minutes based on the max(readtime) in the table (but also will only show real values if the time is a multiple of 5 and is at :00.000 seconds.) For the most part, this is fine, but sometimes the data will get out of sync and cause a bunch of 0 values in our table.

Currently, we've just been going in, grabbing the latest readtime, and hardcoding the new date that we'd like to use. I'm looking for a script I can use to automate this. For the purposes of this question, we can use GETDATE().

DECLARE @readtime DATETIME = GETDATE()  --2011-08-09 08:51:19.237
             -- I want it to look like    2011-08-09 08:50:00.000
like image 276
Tom Avatar asked Aug 09 '11 12:08

Tom


People also ask

How do I add hours minutes and seconds in SQL?

We can use DATEADD() function like below to add hours to DateTime in Sql Server. DATEADD() functions first parameter value can be hour or hh all will return the same result.

How can I update a DateTime field in SQL?

To update with the current date and time: UPDATE table_name SET date_field = CURRENT_TIMESTAMP; To update with a specific date value: UPDATE table_name SET date_field = 'YYYY-MM-DD HH:MM:SS.

How can I add 30 minutes to current date in SQL?

To add minutes to a datetime you can use DATE_ADD() function from MySQL. In PHP, you can use strtotime(). select date_add(yourColumnName,interval 30 minute) from yourTableName; To use the above syntax, let us create a table.

How can add seconds to DateTime in SQL?

We can use DATEADD() function like below to add seconds to DateTime in Sql Server. DATEADD() functions first parameter value can be second or ss or s all will return the same result.


2 Answers

Try this.

It basically checks minutes to be divisible by 5, seconds by 6 and ms by 1000, and if they aren't it subtracts the remainder from each:

DECLARE @dt datetime = '2011-08-09 08:51:19.237'

SELECT DATEADD(
                MILLISECOND, 
                -(DATEPART(MILLISECOND, @dt) % 1000), 
                DATEADD(
                        SECOND, 
                        -(DATEPART(second, @dt) % 60), 
                        DATEADD(
                                minute, 
                                -(DATEPART(minute, @dt) % 5), @dt )
                        )
                )

Output:

2011-08-09 08:50:00.000

like image 83
JNK Avatar answered Nov 09 '22 05:11

JNK


Round down to nearest 5 minute.

DECLARE @readtime DATETIME = 
    DATEADD(minute, 5*FLOOR(DATEDIFF(minute, 0, GETDATE())/5.0), 0)
like image 22
Mikael Eriksson Avatar answered Nov 09 '22 05:11

Mikael Eriksson