Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL DATETIME Math

Tags:

sql

sql-server

I am trying to do the following:

  • Format GetDate() to display only the minutes
  • Format a varchar column to display only the minutes
  • Subtract the current time HH:MM:SS from GetDate() and the VarChar column

This is what I have

CONVERT(VARCHAR(5), GETDATE(), 108) - substring(convert(varchar(20), ColumnName, 9), 13, 5)

but I am getting this error and need some help please:

Operand data type varchar is invalid for subtract operator.

like image 669
user1572695 Avatar asked Aug 30 '26 04:08

user1572695


1 Answers

What you want is datepart(mi).

To get the minutes for getdate():

select datepart(mi, getdate())

To subtract a number of minutes from a datetime:

select dateadd(mi, - <minutes>, <datevalue>)

To remove the time from getdate(), just cast to date (in more recent versions of SQL Server):

select cast(getdate() as date)

To get the difference in minutes, use datediff:

select datediff(mi, <datestart>, <dateend>)

What are you really trying to accomplish?

like image 65
Gordon Linoff Avatar answered Aug 31 '26 22:08

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!