本文實例講述了C#獲取上個月第一天和最后一天日期的方法。分享給大家供大家參考。
具體實現代碼如下:
復制代碼代碼如下:
int year = DateTime.Now.Year;//當前年
int mouth = DateTime.Now.Month;//當前月
int beforeYear = 0;
int beforeMouth = 0;
if (mouth <= 1)//如果當前月是一月,那么年份就要減1
{
beforeYear = year - 1;
beforeMouth =12;//上個月
}
else
{
beforeYear = year;
beforeMouth = mouth - 1;//上個月
}
string beforeMouthOneDay = beforeYear + "年" + beforeMouth + "月" + 1 + "日";//上個月第一天
string beforeMouthLastDay = beforeYear + "年" + beforeMouth + "月" + DateTime.DaysInMonth(year, beforeMouth) + "日";//上個月最后一天
上個月最后一天也可以這樣寫:
復制代碼代碼如下:
string beforeMouthLastDay = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddDays(-1).ToString("yyyy-MM-dd"); //獲取上個月最后一天日期
希望本文所述對大家的C#程序設計有所幫助。