skip to Main Content

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 ?

2

Answers


  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

    Login or Signup to reply.
  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()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search