Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2004-03-31
5
Medium Priority
?
2,645 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
  • 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 200 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses

783 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