0

I am trying to do a notification whenever it is the 1st day of every month but I am having errors at the current moment.

The error I face is that every last day of the same month it keeps stating that is is a new month which is not the result I am expecting

I will put my code here

DateTime firstDayOfnextMonth = new DateTime(
     DateTime.Today.Year, 
     DateTime.Today.Month,
     DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month));

if (DateTime.Today == firstDayOfnextMonth)
{
    MessageBox.Show("Its a new month");
}
else
{
    MessageBox.Show("Its old month");
}

Error img

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
w jx
  • 1
  • The name of "last day of the current month" variable you have is very strange - `firstDayOfnextMonth`... You may want to re-read https://stackoverflow.com/questions/24245523/getting-the-first-and-last-day-of-a-month-using-a-given-datetime-object to clarify what you are doing to yourself. – Alexei Levenkov Nov 30 '18 at 04:24
  • 1
    Your question sounds weird since first day of the next month can never be today. – Access Denied Nov 30 '18 at 04:43

3 Answers3

7

You can do trigger notification by start date of every months as its always start with day 1.

I hope this will help you.

        if (DateTime.Now.Day == 1)
        {
            MessageBox.Show("Its a new month");
        }
        else {
            MessageBox.Show("Its old month");
        }
AGH
  • 353
  • 1
  • 14
0

Let's break down this code:

DateTime firstDayOfnextMonth = new DateTime(
     DateTime.Today.Year, 
     DateTime.Today.Month,
     DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month));

For today's date, DateTime.Today will return 2018/11/30. Thus, DateTime.DaysInMonth() will return 30.

Constructing a DateTime with year 2018, month 11, and date 30 will, of course create a date object representing 2018/11/30, not 2018/12/01 as you seem to expect.

As AGH said in their answer, you should simply check if DateTime.Now.Day == 1.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
0

If you still looking for the first day of the next month you can try the following approach:

DateTime d = new DateTime(2018, 12, 20);//or DateTime.Today...
DateTime firstDayOfnextMonth = new DateTime(d.Year + (d.Month) / 12, (d.Month) % 12 + 1, 1);
Access Denied
  • 8,723
  • 4
  • 42
  • 72