Solved

C# -- "Last Day of the Month" Calculation ?

Posted on 2009-07-10
2
478 Views
Last Modified: 2012-05-07
Revise below to get last day of
this month instead of TODAY.
--------------------------------------------
      private void button1_Click(object sender, EventArgs e)
      {
          string today = String.Format("Last Day of this month is {0}", DateTime.Today.ToString("D"));
          MessageBox.Show(today);
      }
0
Comment
Question by:finance_teacher
2 Comments
 
LVL 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 250 total points
ID: 24827691
DateTime lastDayOfThisMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
0
 
LVL 41

Assisted Solution

by:guru_sami
guru_sami earned 250 total points
ID: 24827980
angelIII 's code should work perfectly if you are looking for lastDate of the month..
But if you are looking for last day i.e. mon/tue/wed etc...you should add one more line to that code:

DateTime lastDayOfThisMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
string lastday = lastDayOfThisMonth.DayOfWeek.ToString();

Or here is some more lines of code:

DateTime today = DateTime.Today;
int daysinmonth = DateTime.DaysInMonth(today.Year, today.Month);
int day = today.Day;
DateTime lastDate =today.AddDays(daysinmonth - day);
string lastDay = lastDate.DayOfWeek.ToString();
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now