Solved

On C# DateTime, how many days between d1 and d2?

Posted on 2004-03-31
5
2,640 Views
Last Modified: 2011-09-20
I have two instances of DateTime, d1 & d2.
How to calculate how many days between d1 and d2?

Thanks a lot.

I went to Microsoft website but couldn't find any
help there.

Jennifer
0
Comment
Question by:jfz2004
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 15

Expert Comment

by:Timbo87
ID: 10726817
TimeSpan t = d2 - d1;

TimeSpan has many methods to retrieve the difference in various formats. Check the .NET SDK for more information.
0
 

Author Comment

by:jfz2004
ID: 10726820
thanks.
0
 
LVL 10

Accepted Solution

by:
eternal_21 earned 50 total points
ID: 10726826
Here is a simple method:

  int CountDays(DateTime dateFrom, DateTime dateTo, bool including)
  {
    return ((System.TimeSpan)(dateTo - dateFrom)).Days + (including ? 1 : 0);
  }

  including = true if you want to include the last day (dateTo) in your count.
0
 

Author Comment

by:jfz2004
ID: 10726877
Just looked into TimeSpan.
Seems like TimeSpan doesn't have a constructor that
needs two DateTime.

How to resolve that?
0
 
LVL 10

Expert Comment

by:eternal_21
ID: 10726966
> "Seems like TimeSpan doesn't have a constructor that needs two DateTime."

What are you trying to do, or have you got the problem figured out?
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question