Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the number of days between dates C# [duplicate]

Tags:

date

c#

datetime

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

like image 784
Tomasz Wida Avatar asked Aug 02 '16 01:08

Tomasz Wida


People also ask

How do you calculate the number of days between dates?

A Better and Simple solution is to count total number of days before dt1 from i.e., total days from 00/00/0000 to dt1, then count total number of days before dt2.

How do I calculate the number of days between two dates in C ++?

Number of days = monthDays[date[1]]. monthDays will store the total number of days till the 1st date of the month.

How do I get the difference between two dates in C #?

The difference between two dates can be calculated in C# by using the substraction operator - or the DateTime. Subtract() method. The following example demonstrates getting the time interval between two dates using the - operator.


1 Answers

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;
like image 101
sujith karivelil Avatar answered Sep 23 '22 06:09

sujith karivelil