-2

I have two text box dates (8/11/2014) and (9/11/2014). I want to find the number of days between these two dates. I am getting some string error message. Please help me..

Dwane Marsh
  • 75
  • 15
  • 10
    Convert them to proper DateTime values, then subtract one from the other. – Lasse V. Karlsen Nov 06 '14 at 13:29
  • 1
    Can you post the code along with the error message? My psychic ability is playing up today. – Matthew Watson Nov 06 '14 at 13:29
  • 1
    @Lasse V. Karlsen, If you dont mind please let me know how to convert these string dates into datetime value? – Dwane Marsh Nov 06 '14 at 13:31
  • @DwaneMarsh: http://msdn.microsoft.com/en-us/library/cc165448.aspx Seriously, not to sound snarky here, but at least *try* Google. – David Nov 06 '14 at 13:33
  • 1
    eh, I could understand someone new to programming not knowing how to research libraries. You gotta learn how to learn. – Jonesopolis Nov 06 '14 at 13:34
  • possible duplicate of [Calculate difference between two dates (number of days)?](http://stackoverflow.com/questions/1607336/calculate-difference-between-two-dates-number-of-days) – Sam Hanley Nov 06 '14 at 14:34

2 Answers2

3

Just parse both dates and then substract them and count total days like this:

DateTime date1 =   DateTime.ParseExact(dateString1, "d/M/yyyy", CultureInfo.InvariantCulture);
DateTime date2 =   DateTime.ParseExact(dateString2, "d/M/yyyy", CultureInfo.InvariantCulture);
var days = (int)(date2-date1).TotalDays;
Paweł Reszka
  • 1,557
  • 4
  • 20
  • 41
2

I feel taking risk to answer this but..

You can use DateTime.ParseExact or DateTime.TryParseExact methods to parse your strings and subtract each other and use TimeSpan.TotalDays property. You can use TimeSpan.Days property as well if you are interested in the total days as an int rather than a double.

string txtdate = "8/11/2014";
DateTime dt;
if(DateTime.TryParseExact(txtdate, "d/MM/yyyy",
                          CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{

}
string txtdate1 = "9/11/2014";
DateTime dt1;
if(DateTime.TryParseExact(txtdate1, "d/MM/yyyy",
                          CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt1))
{

}

var totaldays = (dt1 - dt).Days; // 1

You said;

I need output as 8/11/2014-9/11/2014=1. But I applied your code it shows output like 1.0?

I told you TotalDays property returns double and Days property returns int. But besides that, you seems like a result as 9/11/2014 - 8/11/2014 = 1 instead of just 1. In such a case, you can use string.Format like;

var result = string.Format("{0} - {1} = {2}",
                           dt1.ToString("d/MM/yyyy", CultureInfo.InvariantCulture),
                           dt.ToString("d/MM/yyyy", CultureInfo.InvariantCulture),
                           totaldays);

result will be 9/11/2014 - 8/11/2014 = 1

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364