user3127554
user3127554

Reputation: 577

C# Get last day of previous month given a month and year

I'm trying to create a method that returns me a DateTime object.

This date should be the last day of the previous month (month is given by me).

Example:

Month: january (1)

Year: 2019

What I need: 31/12/2018

This is what I have

   public DateTime getLastDayPrevMonth(int month, int year)
        {
            DateTime date = new DateTime();
            date.Month == month;
            date.Year == year;
            date.AddMonths(-1);
            date.Day = DateTime.DaysInMonth(date.Year,date.Month);

            return date;
        }

but it returns the error:

Only assignment, call, increment, decrement, and new object expressions can be used as a statement

What am I doing wrong?

Upvotes: 1

Views: 2751

Answers (2)

ArunPratap
ArunPratap

Reputation: 5020

you can get Current Date like

var CurrentDate= DateTime.Now; 

and first day of Current Month like

var FirstdayOfThisMonth= new DateTime(CurrentDate.Year, CurrentDate.Month, 1);

and you can add -1 that will return last day of previous month like

var lastDayOfLastMonth = FirstdayOfThisMonth.AddDays(-1);

Upvotes: 4

Tobias Tengler
Tobias Tengler

Reputation: 7454

How about:

public DateTime GetLastDayPrevMonth(int month, int year)
{
    return new DateTime(year, month, 1).AddDays(-1);
}

This creates a new DateTime Object for the first day in the given Month/Year. Then it subtracts one day off of the first day of the month, leaving you with the last day of the previous month.

Upvotes: 5

Related Questions