Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hallo Guy please i need your help.

I want to calculate a difference between a date and a duration like this.
C#
DateTime date_Of_End = new DateTime(2012, 6, 02);
int duration  = 30;

DateTime date_Of_Bigin = date_Of_End - duration ;


Please i get a failure how can i do? have somebody an idea??
Posted

Adding to what VJ Reddy explained, I usually prefer to use TimeSpan[^]. It gives you flexibility when you want to have more accurate calculations. For eg. 30 days, 10 hours and 45 mins :)

C#
DateTime date_Of_End = new DateTime(2012, 6, 02);

int duration  = 30;

TimeSpan tsDay = newTimeSpan(duration, 0, 0, 0);
 
DateTime date_Of_Bigin =  date_Of_End.Subtract(tsDay);
 
Share this answer
 
Comments
Linto Leo Tom 2-Jun-12 11:49am    
You spiced it with more pepper and garlic... Good one. :) +5
Manas Bhardwaj 2-Jun-12 11:53am    
Thanx!
VJ Reddy 2-Jun-12 11:51am    
Good answer. 5!
Manas Bhardwaj 2-Jun-12 11:53am    
Thanx!
Prasad_Kulkarni 3-Jun-12 1:33am    
5'ed
If it is required to deduct 30 days from the Date, then I think the AddDays method of DateTime class with negative number can be used as the Substract method of DateTime accepts a DateTime object and not a duration.
C#
DateTime date_Of_End = new DateTime(2012, 6, 02);
DateTime date_Of_Bigin = date_Of_End.AddDays(-30);
Console.WriteLine (date_Of_Bigin.ToString("dd/MM/yyyy",
	System.Globalization.CultureInfo.InvariantCulture));
//Output
//03/05/2012
 
Share this answer
 
Comments
Umer Aziz Malik 2-Jun-12 11:24am    
A much detailed and robust solution. +5
VJ Reddy 2-Jun-12 11:51am    
Thank you, Umer :)
Linto Leo Tom 2-Jun-12 11:38am    
You are absolutely right VJ...
VJ Reddy 2-Jun-12 11:51am    
Thank you, Linto :)
Manas Bhardwaj 2-Jun-12 11:45am    
nice. +5.
Hi,

You can try this.

To Add :- date_Of_End .AddDays(30)

To Subtract :- date_Of_End .Subtract(30)

Happy Coding
:)
 
Share this answer
 
Comments
Umer Aziz Malik 2-Jun-12 11:24am    
Good answer Linto. Spot on :) +5
Linto Leo Tom 2-Jun-12 12:03pm    
Thanx Umer... :)
Prasad_Kulkarni 3-Jun-12 1:32am    
Good one +5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900