Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total days (int) between DateTime.Now and a certain DateTime [closed]

Tags:

c#

datetime

linq

How can I get the total days as int between DateTime.Now and a specific DateTime? Can this be done using LINQ?

like image 715
user2818430 Avatar asked Oct 13 '13 18:10

user2818430


People also ask

What is the difference between DateTime and DateTime?

You can't create a DateTime without any value (ie, null). It will always have a default value ( DateTime. MinValue ). A DateTime? , on the other hand, is a sort of wrapper around DateTime , which allows you to keep it undefined.

How do you use DateTime DaysInMonth?

The DaysInMonth method always interprets month and year as the month and year of the Gregorian calendar even if the Gregorian calendar is not the current culture's current calendar. To get the number of days in a specified month of a particular calendar, call that calendar's GetDaysInMonth method.

How do I get the difference in days between two dates in C#?

Use DateTime. Subtract to get the difference between two dates in C#.


2 Answers

You can simply calculate the difference using the following method:

DateTime a = ;//some datetime
DateTime now = DateTime.Now;
TimeSpan ts = now-a;
int days = Math.Abs(ts.Days);
like image 120
Willem Van Onsem Avatar answered Oct 10 '22 09:10

Willem Van Onsem


Simply subtract two DateTimes from each other, into a TimeSpan, and get the TotalDays component from it.

TimeSpan diff = DateTime.Now - OtherDateTime
int days = (int)Math.Abs(Math.Round(diff.TotalDays));

It is rounded to remove the fraction caused by the hours/minutes/seconds, and the absolute value is given so you get the exact change.

like image 37
Cyral Avatar answered Oct 10 '22 08:10

Cyral