Home > Blockchain >  Am I using the wrong variable type when calculating dates?
Am I using the wrong variable type when calculating dates?

Time:04-14

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.

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?

CodePudding user response:

You are using the right data type. Datetime is a class with various properties: one of them is Day, which is an integer.

So if we were to have 2 instances of type Datetime, they will in turn have a member called day, which are both integers. In this case, since you have to subtract 2 integers, the result must be saved inside an integer type variable.

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;
}
  • Related