Ali Vojdanian
Ali Vojdanian

Reputation: 2111

subtract two datetime

I use these following codes in the winform for subtracting two datetime. these are complete datetime which includes day and month and year in it. I want to know how can I subtract two date time only with day and month. For example subtract of 5/12 and 6/12 without any year in it.

        DateTime date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
    DateTime datenow =  DateTime.Now;
TimeSpan timeSpan = datenow - date1;

Please give me some codes so that I can subtract two datetime with its day and month.

Thanks in advance

Upvotes: 1

Views: 2742

Answers (2)

Lav
Lav

Reputation: 1896

You can use some default year like datetime.now and do the subtraction like normal. This wouldnt work for non leap years though as 2012 is leap year.

 DateTime dt1= new DateTime(DateTime.Now.Year, month1, day1);
 DateTime dt2= new DateTime(DateTime.Now.Year, month2, day2);
 TimeSpan t= dt1 - dt2;

Upvotes: 0

Chaim Zonnenberg
Chaim Zonnenberg

Reputation: 1823

Try this:

int year = DateTime.Now.Year;
DateTime dt1 = new DateTime(year, month1 , day1);
DateTime dt2 = new DateTime(year, month2,  day2);
int days = (int) Math.Round((dt1 - dt2).TotalDays);

Upvotes: 2

Related Questions