zoukankan      html  css  js  c++  java
  • How to Get First and Last Day of a Month in SQL Server

    To get the first day of the previous month in SQL Server, use the following code:

    SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0)

    first_day_of_last_month

    To get the last day of the previous month:

    SELECT DATEADD(DAY, -(DAY(GETDATE())), GETDATE())

    last_day_of_last_month

    To get the first day of the current month:

    SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)

    first_day_of_current_month

    To get the last day of the current month:

    SELECT DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))

    last_day_of_current_month

     

    To get the first day of the next month:

    SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0)

    first_day_of_next_month

    To get the last day of the next month:

    SELECT DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 2, 0))

    last_day_of_next_month

    In SQL Server 2012 and later you can use EOMONTH Function to Get First and Last Day of a Month in SQL Server:

    Here is an example how you can get the last day of the month you specify, using EOMONTH function:

    DECLARE @Date1 datetime
    SET @Date1 = '04/27/2014'
    SELECT EOMONTH (@Date1)

    eomonth_specified_date

     

    To get the last day of the current month using EOMONTH function:

    SELECT EOMONTH (GETDATE())

    To get the last day of the previous month specify offset -1:

    SELECT EOMONTH (GETDATE(), -1)

    To get the last day of the next month specify offset 1:

    SELECT EOMONTH (GETDATE(), 1)

    EOMONTH function can also be used to calculate the first day of the month. Here is an example:

    DECLARE @Date1 datetime
    SET @Date1 = '04/27/2014'
    SELECT DATEADD(DAY, 1, EOMONTH(@Date1, -1))

    eomonth_specified_date_first_day

  • 相关阅读:
    Master公式计算递归时间复杂度
    对数器的使用
    HTML翻转菜单练习
    剑指offer题目解答合集(C++版)
    HTML---仿网易新闻登录页
    两个有序数组中的中位数以及求第k个最小数的值
    算法之重建二叉树
    AFNetWorking 上传功能使用及源码分析
    图片Alpha预乘的作用[转]
    C#/.NET 学习之路——从入门到放弃
  • 原文地址:https://www.cnblogs.com/zhangyuefen/p/5056382.html
Copyright © 2011-2022 走看看