C# 如何将两个日期之间的差异显示为00Y 00M
给定两个C#的日期时间,如何显示年和月的差异 我可以用一个简单的减法来计算时间跨度,但这不会考虑不同的月长、闰年等 谢谢您的帮助。您可以尝试以下方法:C# 如何将两个日期之间的差异显示为00Y 00M,c#,datetime,C#,Datetime,给定两个C#的日期时间,如何显示年和月的差异 我可以用一个简单的减法来计算时间跨度,但这不会考虑不同的月长、闰年等 谢谢您的帮助。您可以尝试以下方法: 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;
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);
因为从公元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);
不同的月长?需要几个月?时间跨度不限于一年中的某一年或某个月。您只能计算两个日期之间的天数:
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);
//原语,不雅观,但在date1
这里的问题是,你只是忽略了日子。毕竟这不是一个好的解决方案。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);
假设在本例中是UTC日期时间 (您还可以为“现在”定义任何不同的日期) 如果在生日中有定义,您可以继续使用小时、分钟、秒等 现在可以从年龄中提取年、月、日
int years = age.Year
int month = age.Month
诸如此类你能给出一个你期望的日期和输出的例子吗?我认为从MinValue开始是不正确的。您得到一个值,但它与当前月份无关。当然,差别很小,大约是28天,而不是31天。但是你也可以用蜱把一年分成12个大小相同的部分。。。
int years = age.Year
int month = age.Month