tags:

views:

447

answers:

2

For example:

DateTime date1 = new DateTime(1955, 12, 12);
DateTime date2 = new DateTime(1967, 3, 6);
TimeSpan fff = date2 - date1;

Will it calculate number of days correctly? (taking leap year into account)

+6  A: 

Yes, it takes this into account.

For proof, try:

DateTime date0 = new DateTime(2001, 12, 31);
DateTime date1 = new DateTime(2000, 12, 31);
DateTime date2 = new DateTime(1999, 12, 31);
Console.WriteLine("{0} / {1}", (date2 - date1).Days, (date1-date0).Days);

The above outputs: -366 / -365

Reed Copsey
It would be horribly broken if it didn't, but worse things have been done (see Oracle's MONTHS_BETWEEN() function for some interesting behaviour!).
Jonathan Leffler
I guess I've got confused by this post here: http://stackoverflow.com/questions/1083955/how-to-get-difference-between-two-dates-in-year-month-week-day/1083991#1083991Jon Skeet mentioning about leap years, and such, but I think they're talking about finding out number of days, weeks and months..not just days
Speaking of horribly broken; DateTime computations silently ignore timezone issues (comparing local datetimes to utc datetimes is legal, but doesn't do "the right thing")
Eamon Nerbonne
A: 

I would suggest that a nice complementary tool to your C# development environment would be to download Boo. Boo is a Pythonesque scripting language, but with full access to the .NET framework. I've used it quite a bit as a help in quickly trying out string formatting, regular expressions, and date/time string formatting. Here is my Boo session where I tested out your question:

C:\Documents and Settings\Paul>booish
Welcome to booish, an interpreter for the boo programming language.
Running boo 0.9.0.3203 in CLR v2.0.50727.3082.

Enter boo code in the prompt below (or type /help).
>>>dt1 = System.DateTime(2009,1,1)
1/1/2009 12:00:00 AM
>>>dt2 = System.DateTime(2008,1,1)
1/1/2008 12:00:00 AM
>>>dt3 = System.DateTime(2007,1,1)
1/1/2007 12:00:00 AM
>>>print dt1-dt2
366.00:00:00
>>>print dt2-dt3
365.00:00:00
>>>

You can also compile Boo scripts to DLLs and EXEs.

Paul McGuire