C# - 获取两个日期,然后仅减去年份

标签 c# date

我想获取年份,但没有TotalYears在日期时间所以我在这里试试我的运气。 我正在做的是从这样的表单中输入日期

DateTime acquisition = DateTime.Parse(Request.Form["inputAcquisition"]);

然后是今天的日期,这样它将减去获取日期。

 DateTime now = DateTime.Now;

现在这是让我感到困惑的部分。减去它们

TimeSpan difference = now - acquisition ;

我收到了一些值(value),但它就像 2819:012:23123:1246 的胡言乱语。//不是实际数据。

如何才能得到当年的总差值?如果我输入 2014 年 3 月 20 日,减去今天的年份,我将得到 3作为输出?

最佳答案

使用如下:

//Option 1 - Just Years only
DateTime current = DateTime.Now;
DateTime d = new DateTime(2014, 2, 20);
int yearDiff = current.Year - d.Year;
Console.WriteLine("Difference in Years: " + yearDiff);

// Option 2 - More precise
long diff = current.Ticks - d.Ticks;
DateTime yearDiff2 = new DateTime(diff);
Console.WriteLine("Difference in Years: " + yearDiff2.Year);

类似问题:Calculate the difference between two dates and get the value in years?

关于C# - 获取两个日期,然后仅减去年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42776911/

相关文章:

c# - SqlConnection 忽略用户的默认架构

php - 从日期数组中查找上一个和下一个最近的日期

Javascript 日期到 IS8601 格式?

iphone - iOS从日期获取时间

c# - 索引 0 为负数或高于行数

c# - 使用 win32 API 函数启用/禁用任务管理器,而不是通过 Windows 注册表

c# - 存储过程参数名称是否必须与从 C# 传递的参数匹配?

c# - Type.GetType() 不适用于非本地类型?

java - 如何将 Timestamp 转换为 Date 或 DateTime 对象?

bash - 如何将日期附加到 bash 中的字符串