13

I have a string that coming in date format date=08/21/2016 what I want to do is find the numbers of days From today's date in C# I have converted the string like this.

 DateTime Date = Convert.ToDayTime("08/21/2016"); 
 DateTime TodayDate = DateTime.Today.Day;    
 DateTime SubDate = Date.Subtract(TodayDate);

On the third line, I'm getting error cannot convert System.TimeSpan to System.DateTime

Is there an another way to do this what I want to do I just calculate numbers of days from a future date that is coming as a string

 Example 
 TodayDate=08/01/2016
 FutureDate=08/20/2016

 Answer 19 days 

I'm new to C# if it's not to much trouble could somebody share code solution how to achieve this? Thanks for the help

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Tomasz Wida
  • 329
  • 1
  • 6
  • 24

2 Answers2

27

There is no method called Convert.ToDayTime in the Convert class it should be Convert.ToDateTime().

The DateTime allows you to subtract its object from another object of the same type. then You can make use of the .TotalDays function to get the number of days. between those dates.

Use something like this:

DateTime futurDate = Convert.ToDateTime("08/21/2016");
DateTime TodayDate = DateTime.Now;
var numberOfDays = (futurDate - TodayDate).TotalDays;
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
4
DateTime FutureDate = DateTime.ParseExact("08/21/2016", "mm/dd/yyyy", CultureInfo.InvariantCulture);
DateTime TodayDate = DateTime.Now;

int days = (FutureDate - TodayDate).Days;
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541