How to get last day of current month in C# Asp.net?
Hello, I create a admin page help report information about order of the daily, weekly, monthly and quater. I created a project with C# .Net 6 but I stuck when choose monthly option. I don't know how to get the last day of the current month in C#.
I tried to use
DateTime.Now.Day but it return the current day not last day of the current month.
Thank for any solution.
Noe Giron May 18 2022
You can use
DaysInMonth()to help return total day of the moth (it's same with last day of the month), see example below:
int lastDayOfMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
This code will return last day of the current month. If you want to get last day of any other month, you need to change year & month parameter for function above.
I hope this answer is helpful for you.
Mukul Pundir May 18 2022
It seem easy. You can see code and fomular below:
DateTime now = DateTime.Now; // get current time var firstDayOfTheMonth = new DateTime(now.Year, now.Month, 1); // Get first day var LastDayOfTheMonth = firstDayOfTheMonth.AddMonths(1).AddDays(-1); // Last day = firstday + 1 month - 1 day.
It really worked for me.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.