Month last day

johnkainn
johnkainn used Ask the Experts™
on
I would like to find date of the last day of the month. How do I do that in C#
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:

I've attached some code. If it's the date of the last day in THIS month, use

DateTime lastDay = LastDayInMonth(DateTime.Today);

See also System.Threading.Thread.CurrentThread.CurrentCulture.Calendar.GetDaysInMonth(...)
public static DateTime LastDayInMonth(DateTime date)
{
    DateTime nextMonth = date.AddMonths(1);
    return new DateTime(nextMonth.Year, nextMonth.Month, 1).AddDays(-1);
}

Open in new window

Commented:
This would do it :

      DateTime d = DateTime.Parse(DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month).ToString() + "/"+ DateTime.Now.Month.ToString() + "/" + DateTime.Now.Year.ToString());
Commented:
DateTime today = DateTime.Today;
DateTime lastDayOfThisMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
High School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009
Commented:
I like BurnieP's use of DateTime.DaysInMonth() but I would use it like this:
*overloaded so you can pass in either a DateTime or a Year/Month
        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine(LastDayInMonth(DateTime.Today).ToString());
        }

        private DateTime LastDayInMonth(DateTime dt)
        {
            return LastDayInMonth(dt.Year, dt.Month);
        }

        private DateTime LastDayInMonth(int year, int month)
        {
            try {
                return new DateTime(year, month, DateTime.DaysInMonth(year, month)); 
            }
            catch (Exception ex) {
                return DateTime.MinValue;
            }
        }

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial