【发布时间】:2009-04-21 08:39:49
【问题描述】:
给定 C# 中的两个 DateTimes,我如何显示年和月的差异?
我可以对来自简单减法的时间跨度进行基本算术运算,但这不会考虑月份、闰年等的不同长度。
感谢您的帮助。
【问题讨论】:
-
您能否发布一个您期望的日期和输出示例?
给定 C# 中的两个 DateTimes,我如何显示年和月的差异?
我可以对来自简单减法的时间跨度进行基本算术运算,但这不会考虑月份、闰年等的不同长度。
感谢您的帮助。
【问题讨论】:
由于基础表示是自公元 1 年 1 月 1 日午夜 12:00 起以 100 纳秒的刻度测量的,因此减法将非常正确地处理闰年等:
DateTime date1 = ...
DateTime date2 = ...
// date2 must be after date1
TimeSpan difference = date2.Subtract(date1);
DateTime age=new DateTime(tsAge.Ticks);
int years = age.Years - 1;
int months = age.Month - 1;
Console.WriteLine("{0}Y, {1}M", years, months);
【讨论】:
FWIW 这就是我最终得到的结果
DateTime servicelength = new DateTime(DateTime.Now.Subtract(employee.StartDate).Ticks);
LengthOfService.Text = String.Format("{0}Y {1}M", servicelength.Year - 1, servicelength.Month - 1);
【讨论】:
你可以试试这个:
DateTime date1 = new DateTime(1954, 7, 30);
DateTime today = DateTime.Now;
TimeSpan span = today - date1;
DateTime age = DateTime.MinValue + span;
int years = age.Year - 1;
int months = age.Month - 1;
int days = age.Day - 1;
Console.WriteLine("years: {0}, months: {1}, days: {2}", years, months, days);
【讨论】:
不同的月份长度?应该用哪个月?时间跨度不限于一年中的某一年或某月。您只能计算两个日期之间的天数:
Timspan span = date2 - date1;
Console.Writeline("Days between date1 and date2: {0}", span.Days);
从 DateTime.MinValue 开始计算,只需以 0001 年为起点,从 1 月开始计算月份。我不认为这有实际用途。
编辑:
有另一个想法。您可以计算自 date1 以来的月份:
// primitive, inelegant, but should work if date1 < date2
int years = date2.Year - date1.Year;
int month = date2.Month - date1.Month;
if (month < 0)
{
years -= 1;
month += 12;
}
Console.Writeline("{0}Y {1}M", years, month);
这里的问题是你忽略了这些日子。毕竟这不是一个好的解决方案。
【讨论】:
在这个例子中它是 UTC 日期时间 (您也可以为“现在”定义任何不同的日期)
DateTime now = DateTime.UtcNow;
DateTime birthdate = new DateTime (1976,11,12);
DateTime age = now.AddYears(-birthdate.Year).AddMonths(-birthdate.Month).AddDays(-birthdate.Day);
如果在生日中定义,您可以继续使用小时、分钟、秒等
现在您可以从年龄中提取年月日
int years = age.Year
int month = age.Month
等等
【讨论】: