Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate seconds and milliseconds in SQL

I'm having a bit of trouble with truncating data. I'm using SQL's GETDATE() function to get the current date and time and enter them into a database. However, I only want to save the date and time up until the minute. In other words, I want dd/mm/yyyy hh:mm:00.000 or dd/mm/yyyy hh:mm to be saved when I input new data. How can I go about doing this?

I should note I'm using MS-SQL.

like image 344
Ultracoustic Avatar asked Jun 30 '14 18:06

Ultracoustic


People also ask

How do you subtract seconds in SQL?

Other Ways to Subtract SecondsThe SUBTIME() function. The ADDTIME() function (providing a negative amount will subtract that amount from the datetime value). The SUBDATE() function (this is a synonym for DATE_SUB() when used with the same syntax).

How can I get time without seconds in SQL?

How can I get time without seconds in SQL? it is always stored the only thing you can do is to edit the value before it gets posted so the seconds (and also the milliseconds which are also stored) are set to 0. I suggest you to use two columns for: Hour & Minute ;).


1 Answers

There are a number of ways to go about doing this.

For example, you could convert the generated datetime from GetDate() to a smalldatetime first, à la:

CAST(GetDate() AS smalldatetime)

To be clear, this will round the generated seconds up (or down) to the nearest minute depending up the value of the current second.

EDIT:

Alternatively, you can have SQL Server truncate a datetime for you for a "cleaner" (READ: no rounding, since the value is pre-truncated) conversion to smalldatetime:

CAST(DateAdd(minute, DateDiff(minute, 0, GetDate()), 0) AS smalldatetime)
like image 93
László Koller Avatar answered Sep 19 '22 16:09

László Koller