首页 > 代码库 > 获取指定日期所在月份的第一天
获取指定日期所在月份的第一天
获取指定日期月份的第一天,你可以使用DATEADD函数,减去指定日期的月份过去了的天数,即可。
CREATE FUNCTION [dbo].[udf_FirstDayOfMonth]
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN CAST(DATEADD(day,1 - DAY(@Date), @Date) AS DATETIME)
END
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN CAST(DATEADD(day,1 - DAY(@Date), @Date) AS DATETIME)
END
CREATE FUNCTION [dbo].[udf_FirstDayOfMonth]
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN CAST(DATEADD(day,1 - DAY(@Date), @Date) AS DATETIME)
END
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN CAST(DATEADD(day,1 - DAY(@Date), @Date) AS DATETIME)
END
或者,用DATEDIFF计算指定日期与日期开始之时,相隔几个月,然后再DATEADD加上这个相隔月份数,从零开始。
CREATE FUNCTION [dbo].[udf_FirstDayOfMonth]
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MONTH,DATEDIFF(MONTH,0,@Date),0)
END
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MONTH,DATEDIFF(MONTH,0,@Date),0)
END
CREATE FUNCTION [dbo].[udf_FirstDayOfMonth]
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MONTH,DATEDIFF(MONTH,0,@Date),0)
END
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MONTH,DATEDIFF(MONTH,0,@Date),0)
END
或者,从指定的日期取出年或月,然后与01组合为日期,即得到指定日期当月天第一天。
CREATE FUNCTION [dbo].[udf_FirstDayOfMonth]
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @y NVARCHAR(4) = CAST(YEAR(@Date) AS NVARCHAR(4))
DECLARE @m NVARCHAR(2) = CAST(MONTH(@Date) AS NVARCHAR(2))
RETURN CAST((@y + N‘-‘ + @m + N‘-01‘) AS DATETIME)
END
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @y NVARCHAR(4) = CAST(YEAR(@Date) AS NVARCHAR(4))
DECLARE @m NVARCHAR(2) = CAST(MONTH(@Date) AS NVARCHAR(2))
RETURN CAST((@y + N‘-‘ + @m + N‘-01‘) AS DATETIME)
END
CREATE FUNCTION [dbo].[udf_FirstDayOfMonth]
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @y NVARCHAR(4) = CAST(YEAR(@Date) AS NVARCHAR(4))
DECLARE @m NVARCHAR(2) = CAST(MONTH(@Date) AS NVARCHAR(2))
RETURN CAST((@y + N‘-‘ + @m + N‘-01‘) AS DATETIME)
END
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @y NVARCHAR(4) = CAST(YEAR(@Date) AS NVARCHAR(4))
DECLARE @m NVARCHAR(2) = CAST(MONTH(@Date) AS NVARCHAR(2))
RETURN CAST((@y + N‘-‘ + @m + N‘-01‘) AS DATETIME)
END
或者,参考这篇:http://www.cnblogs.com/insus/articles/1554836.html 使用CONVERT函数,指定日期格式来转换,这样也可以获取指定日期所在月份的第一天。
CREATE FUNCTION [dbo].[udf_FirstDayOfMonth]
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @ym NVARCHAR(10) = CONVERT(varchar(8),GETDATE(),23)
RETURN CAST((@ym + N‘01‘) AS DATETIME)
END
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @ym NVARCHAR(10) = CONVERT(varchar(8),GETDATE(),23)
RETURN CAST((@ym + N‘01‘) AS DATETIME)
END
CREATE FUNCTION [dbo].[udf_FirstDayOfMonth]
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @ym NVARCHAR(10) = CONVERT(varchar(8),GETDATE(),23)
RETURN CAST((@ym + N‘01‘) AS DATETIME)
END
(
@Date DATE
)
RETURNS DATETIME
AS
BEGIN
DECLARE @ym NVARCHAR(10) = CONVERT(varchar(8),GETDATE(),23)
RETURN CAST((@ym + N‘01‘) AS DATETIME)
END
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。