The first day of the month on which the given date is calculated
The trick is to calculate the
number of time intervals between the current date and "1900-01-01" and then add it to "1900-01-01" to get a special date, a technique that can be used---to calculate many different dates.
DECLARE @date datetime
Set @date =getdate ()
Select DATEADD (Month,datediff (month, ' 1900-01-01 ', @date), ' 1900-01-01 ') as ' the first day of the month '
--streamlined algorithm, based on the time representation of SQL Server, "1900-01-01" can be replaced by 0
Select DATEADD (Month,datediff (month,0, @date), 0) as ' the first day of the month '
--The above two algorithms are accurate to the timing of 00:00:00.000
--The following algorithm class to keep time and seconds
--Train of thought: Subtract the number of days from the first day of the month from the given date with a given date
Select DATEADD (Day,1-datepart (Day, @date), @date)
Go
-month end, calculates the last day of the month for the given date
DECLARE @date datetime
Set @date =getdate ()
--Train of thought: Next January 1 in the current month minus 1 days
Select DATEADD (Day,-1,dateadd (Month,1+datediff (month, ' 1900-01-01 ', @date), ' 1900-01-01 ')) as ' The Day of the month '
Select DATEADD (Month,1+datediff (month, ' 1900-01-01 ', @date), ' 1900-01-01 ')-1 as ' The Day of the month '
--1900-01-01 with 0 instead
Select DATEADD (Day,-1,dateadd (Month,1+datediff (month,0, @date), 0)) as ' The Day of the month '
Select DATEADD (Month,1+datediff (month,0, @date), 0)-1 as ' The Day of the month '
--Train of thought: Same as the beginning of the month
Select DATEADD (Month,datediff (month, ' 1989-12-31 ', @date), ' 1989-12-31 ') as ' the Day of the month '
--Streamlined algorithm, ' 1989-12-31 ' with 1 instead
Select DATEADD (Month,datediff (month,-1, @date), -1) as ' The Day of the month '
--The algorithm of keeping time and seconds
Select DATEADD (Day,-1,dateadd (Month,1,dateadd (Day,1-datepart (Day, @date), @date))
Go