Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
int currentmonth = DateTime.Now.Month;
            int x = 0;

            if (currentmonth == DateTime.Now.Month)
            {
                x++;
            }
            else
                x = 0;


This is my code. This code is part of a button that adds the value of x to a certain data in the database and if and only if the month changes(ex. current month = March then the next press of the button will be at May) the value of x returns to 0. I don't know how to test this so that I can see if it resets or not. I would like to ask your opinion if the code snippet is correct.

What I have tried:

I've tried to incorporate this in my sql and so far it works. But I can only really know if this snippet is correct if the month changes.
Posted
Updated 1-Mar-16 2:38am
Comments
NPSSR 1-Mar-16 8:31am    
Hi, 'currentmonth' is already initialized with 'Datetime.Now.Month'. May i know, what is the need of checking it again? Anyway, just convert it to Int and try.
[no name] 1-Mar-16 8:35am    
Actually, I don't really know the process of how I'm going to code what I was thinking so I just tried some ideas. From my perspective, the snippet should check if example, March = April if yes then x = 0 then if no x++.
Mehdi Gholam 1-Mar-16 8:31am    
currentmonth will never change in the code posted and x will never be 0.
[no name] 1-Mar-16 8:36am    
What could be a possible solution to this? I don't really know how to put my idea into a code.

1 solution

Um.
So your code gets the current month, and compares it to...the current month.
And you expect it to spot when the month changes?
Well, it will. But only if the month actually changes in the milliseconds (or even nanoseconds) between the two accesses to the DateTime.Now property - which is unlikely in the extreme.
Probably, what you actually want to do is create a private DateTime variable and preset it to the "initial" date:
C#
private DateTime startedAt = DateTime.Now;
Then in your button Click handler just check it:
C#
DateTime now = DateTime.Now;
if (startedAt.Month == now.Month)
   {
   x++;
   }
else
   {
   x = 0;
   startedAt = now;
   }
 
Share this answer
 
Comments
[no name] 1-Mar-16 8:45am    
I tried your code, initially it entered the 1 then when I tried to change the month of my computer to april and tried it again it was still 1. hmmm :/
OriginalGriff 1-Mar-16 9:01am    
So use the debugger and see exactly what is happening when you press the button.
Look at x at the start of the method, then look at startedAt and now immediately before the "if" executes.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900