Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Am I using the wrong variable type when calculating dates?

I have a statement like this:

var currentDate = DateTime.Now;
var futureDate = new DateTime(2022, 8, 18);

int spaceBetweenDays = (futureDate - currentDate).Days;

switch (spaceBetweenDays)
{   
    case 200:
        ...do stuff
        break;
    case 175:
        ...do stuff
        break;
    case 150:
        ...do stuff
        break;
    case 125:
        ...do stuff
        break;
    case 100:
        ...do stuff
        break;
    case 75:
        ...do different stuff

I want to run a block code when the spaceBetweenDays is a certain number.

When testing, I can never get the code to work. Even when the value of spaceBetweenDays is one of the test values(200, 175, 150, etc), it never runs.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So in Visual Studio, when I hover over the numbers after the case statement, It is saying it is a System.Int32.

But spaceBetweenDays is an int.

Could this be why it’s not working?

>Solution :

If you want to test, just add x days to today date. For example:

DateTime current = DateTime.Now;
DateTime futureDate = DateTime.Now.AddDays(200);
    
int daysDiff = (futureDate - current).Days;
    
switch (daysDiff)
{
                    case 200:
                        Console.WriteLine("200");
                        break;
    
                    default:
                        break;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading