SoFunction
Updated on 2025-03-07

C# How to get the first and last day dates of last month

This article example describes how C# obtains the first and last day dates of last month. Share it for your reference.

The specific implementation code is as follows:

Copy the codeThe code is as follows:
int year = ;//Current year
int mouth = ;//Current month
 
int beforeYear = 0; 
int beforeMouth = 0; 
if (mouth <= 1)//If the current month is January, then the year will be reduced by 1

    beforeYear = year - 1; 
beforeMouth =12;//Last month

else 

   beforeYear = year; 
beforeMouth = mouth - 1;//Last month

string beforeMouthOneDay = beforeYear + "Year" + beforeMouth + "month" + 1 + "day";//The first day of last month
string beforeMouthLastDay = beforeYear + "year" + beforeMouth + "month" + (year, beforeMouth) + "day";//Last day of last month

You can also write this on the last day of last month:

Copy the codeThe code is as follows:
string beforeMouthLastDay = (("yyyy-MM-01")).AddDays(-1).ToString("yyyy-MM-dd"); //Get the last day date of the previous month

I hope this article will be helpful to everyone's C# programming.