获取当月的第一天和最后一天示例

最简单获取当月第一天和最后一天 代码如下:

DateTime now = DateTime.Now; DateTime dt1 = new DateTime(now.Year, now.Month, 1); DateTime dt2 = d1.AddMonths(1).AddDays(-1); dt1是本月的第一天,dt2本月的最后一天, 最后一天的算法是:得到本月的第一天然后增加一月,再减去一天.
智能判断每个月有多少天: 

//返回每月的第一天和最后一天 public static void ReturnDateFormat(int month, out string firstDay, out string lastDay) { int year = DateTime.Now.Year + month / 12; if (month != 12) { month = month % 12; } switch (month) { case 1,3,5,7,8,10,12: firstDay = DateTime.Now.ToString(year + "-0" + month + "-01"); lastDay = DateTime.Now.ToString(year + "-0" + month + "-31"); break;
         
case 4,6,9,11: firstDay = DateTime.Now.ToString(year + "-0" + month + "-01"); lastDay = DateTime.Now.ToString(year + "-0" + month + "-30"); break;
        
default:
            //2月
            firstDay = DateTime.Now.ToString(year + "-0" + month + "-01");
                    if (DateTime.IsLeapYear(DateTime.Now.Year))
                        lastDay = DateTime.Now.ToString(year + "-0" + month + "-29");
                    else
                        lastDay = DateTime.Now.ToString(year + "-0" + month + "-28");
                    break;
 } }
原文地址:https://www.cnblogs.com/lxyang/p/5931992.html