使用C#的日期差异 [英] Date difference in years using C#

查看:112
本文介绍了使用C#的日期差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算两个日期之间的日期差异?

How can I calculate date difference between two dates in years?

例如:(Datetime.Now.Today() - 11 /

For example: (Datetime.Now.Today() - 11/03/2007) in years.

推荐答案

我已经写了一个正确使用日期的实现一年的时间。

I have written an implementation that properly works with dates exactly one year apart.

但是,与其他算法不同,它不会优雅地处理负时间戳。它也不使用自己的日期算术,而是依赖于标准库。

However, it does not gracefully handle negative timespans, unlike the other algorithm. It also doesn't use its own date arithmetic, instead relying upon the standard library for that.

所以不用多说,这里是代码:

So without further ado, here is the code:

DateTime zeroTime = new DateTime(1, 1, 1);

DateTime a = new DateTime(2007, 1, 1);
DateTime b = new DateTime(2008, 1, 1);

TimeSpan span = b - a;
// Because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;

// 1, where my other algorithm resulted in 0.
Console.WriteLine("Yrs elapsed: " + years);

这篇关于使用C#的日期差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆