Code examples: Get date minus 1 day
Source: A date in string format, for example, "2015-04-21".
The task: To find a date minus 1 day from the source.
Solution:
C#:
string selDate = "2015-04-21"; DateTime selDateMinusOne = Convert.ToDateTime(selDate).AddDays(-1); //Convert result date to the same format as source: string strSelDateMinusOne = (Convert.ToDateTime(selDate).AddDays(-1)).ToString("yyyy-MM-dd"); console.WriteLine(strSelDateMinusOne)
The result is: 2015-04-20
SQL. SQL date calculations:
In SQL the task like to calculate a date is very popular. For example, you need to get records between dates
The academic example: the query "select DATEADD(DD, -1, '2015-10-15')" will return '2015-10-14'
Practice example: select records since 1 day before '2015-10-15' until 1 day after this date:
SELECT OrderID, CustomerID, EmployeeID, OrderDate, RequiredDate FROM [northwind].[dbo].[Orders] WHERE OrderDate BETWEEN DATEADD(DD, -1, '2015-10-15') AND DATEADD(DD, +1, '2015-10-15')