开发者

Get the number of days between two different DateTime objects

开发者 https://www.devze.com 2023-02-06 02:14 出处:网络
How can I get the difference of days between two DateTime objects? private static string DaysAfterAYear(DateTime initialDate)

How can I get the difference of days between two DateTime objects?

private static string DaysAfterAYear(DateTime initialDate)
{
    DateTime endDate = initialDate.AddYears(1);
    endDate = endDate.AddMonths(1);
    return ??
}

I need to get the difference between initialDate and endDate.开发者_C百科


Use the subtract method:

static void Main(string[] args)
{
    DateTime begin = DateTime.Now;
    DateTime end = begin.AddYears(1).AddMonths(1);
    var result = end.Subtract(begin).TotalDays;
}


DateTime dt1 = new DateTime(2011,01,01);
DateTime dt2 = new DateTime(2011,01,20);
int ireturn = (int)dt2.Subtract(dt1).TotalDays;


Subtracting DateTimes will yield a TimeSpan:

var elapsedDays = (endDate - initialDate).TotalDays;


DateTime start = DateTime.Now;
DateTime end = DateTime.Now.AddDays(5);
TimeSpan span = end.Subtract(start);
return span.Days;


        int days = 10;
        DateTime initialDate = DateTime.Now;
        DateTime endDate = DateTime.Now.AddDays(days);
        TimeSpan duration = endDate.Subtract(initialDate);

In this example you can use either span.Days or span.TotalDays, however you have to be very careful with TimeSpan properties. If you look at the TotalHours vs Hours for example you'll see that they are not the same.

The Hours property is the number of hours remaining after the days property has been taken off (in this case zero), the Total hours is the TimeSpan represented in hours.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号