|
drop function find_end_of_month
go
create function find_end_of_month (@date datetime) returns datetime
as
begin
-- select check_services.dbo.find_end_of_month (getdate())
declare @first_of_month datetime
declare @last_of_month datetime
set @first_of_month = convert(datetime, convert(varchar,datepart(m,@date)) +
'/01/' +
convert(varchar,datepart(yyyy,@date) )
)
-- first of next month...
set @last_of_month = dateadd(m, 1, @first_of_month)
-- ...minus one day
set @last_of_month = dateadd(d, -1, @last_of_month)
return @last_of_month
end
go
For more examples on how to use SQL Server Date functions, DateAdd(), DateDiff(), DatePart(), GetDate() see other Siccolo articles:
- How to Find Beginning and End of Week
- How to Find Number of Days in a Month
Side Note:
DateAdd() - Returns a new datetime value based on adding an interval to the specified date.
Where first parameter specifies on which part of the date to return a new value: yy(yyyy) for Year, mm(m) for Month,
dd(d) for Day etc.
For example: select dateadd(d,2,getdate()) - adds 2 days to current date and returns new date.
DateDiff() - Returns the number of date and time boundaries crossed between two specified dates.
Where DateDiff( <interval>, <start date>, <end date>):
<Start Date> is subtracted from <End Date>. If <Start Date> is later than <End Date>, a negative value is returned.
DatePart() - Returns an integer representing the specified datepart of the specified date.
Where DatePart( <interval>, <Date>)
Where the datepart interval parameter is one of the following:
- year,
- quarter,
- month,
- dayofyear,
- day,
- week,
- hour,
- minute,
- second or
- millisecond.
The number datepart interval parameter is an integer value for the number of dateparts to be added
to or subtracted from the date parameter.
Now depending on your needs, your application might use this function to perform mathematical calculations on a given date.
The DATEDIFF function is used to calculate the number of date and time boundaries crossed between two different dates. This function returns an integer value.
GetDate() - Returns the current system date and time
in the Microsoft� SQL Server� standard internal format for datetime values.
SQL Server provides the GetDate() function to get UTC time.
The GetDate() function returns a
datetime value that represents the current UTC time.
|