C# 获取一年中每月月初和月末时间

C# 获取一年中每月月初和月末时间

 	/// 
    /// 获取每月月初和月末
    /// 
    /// 
    public List<MoTime>  GetMonthData()
    {
        var dataList = new List<MoTime>();
        DateTime dateTime = DateTime.Now;
        var currentMonth = dateTime.Month;//获取当月份
      
        for (int i = 1; i <= 12; i++)
        {
            MoTime time = new MoTime();
            if (currentMonth > i)
            {
                int count = currentMonth-i;
                //上个月,减去一个月份
                DateTime startMonth = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(-count);
                DateTime endMonth = startMonth.AddMonths(1).AddDays(-1);
                time.monthStart = startMonth.ToShortDateString();
                time.monthEnd = endMonth.ToShortDateString();
            }
            if (currentMonth == i)
            {
                DateTime startMonth = dateTime.AddDays(1 - dateTime.Day); //本月月初
                DateTime endMonth = startMonth.AddMonths(1).AddDays(-1); //本月月末
                time.monthStart = startMonth.ToShortDateString();
                time.monthEnd = endMonth.ToShortDateString();
            }
            if (currentMonth < i)
            {
                int count = i - currentMonth;
                //上个月,减去一个月份
                DateTime startMonth = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(count);
                DateTime endMonth = startMonth.AddMonths(1).AddDays(-1);
                time.monthStart = startMonth.ToShortDateString();
                time.monthEnd = endMonth.ToShortDateString();
            }
            dataList.Add(time);
        }         
        return dataList; 
    }

你可能感兴趣的:(后端,c#,开发语言,.net,后端)