'Unable to cast object on getting remaining days

I am trying to get the remaining date to two decimal points

code I tried

(Math.Round((Convert.ToDecimal(DateTime.Now - i.dueDate)),2)).ToString()

Error I am getting

Unable to cast object of type 'System.TimeSpan' to type 'System.IConvertible'.

How can i solve this ?



Solution 1:[1]

Use this snippet code:

    static void Main(string[] args)
    {
        var today = DateTime.Now;
        var sevenDaysAgo = DateTime.Now.AddDays(-7);
        var difference = today - sevenDaysAgo;

        Console.WriteLine(Math.Round(difference.TotalDays, 2, 
              MidpointRounding.ToZero));
    }

Output:

Output is 6.99

Solution 2:[2]

Subtracting two dates yields a TimeSpan which is not directly convertible to a decimal. What value do you want? The number of decimal days? The number of minutes? So you need to be explicit by using the properties of a TimeSpan (like TotalDays):

(Math.Round((DateTime.Now - i.dueDate).TotalDays,2)).ToString()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 D Stanley