C# 在最大日期范围描述中显示两个日期之间差异的最简单方法是什么?
我有以下代码:C# 在最大日期范围描述中显示两个日期之间差异的最简单方法是什么?,c#,timespan,C#,Timespan,我有以下代码: var datesMove = (newState.Milestone- oldState.Milestone).TotalDays; 这显示了两个日期之间的天数 这工作很好,但我显示在网页上,而不是显示 搬迁日期:43天: 我的用户要求查看类似的内容:1个月3天或1年3个月2天 是否有任何内置的助手函数可以接受日期差异,并将其显示在可能的最高聚合级别,如上面的示例?您可以尝试以下代码: DateTime StartDate = Convert.ToDateTime("01/
var datesMove = (newState.Milestone- oldState.Milestone).TotalDays;
这显示了两个日期之间的天数
这工作很好,但我显示在网页上,而不是显示
搬迁日期:43天:
我的用户要求查看类似的内容:1个月3天或1年3个月2天
是否有任何内置的助手函数可以接受日期差异,并将其显示在可能的最高聚合级别,如上面的示例?您可以尝试以下代码:
DateTime StartDate = Convert.ToDateTime("01/1/2010");
DateTime EndDate = Convert.ToDateTime("04/3/2011");
string strResult = CalculateDays(StartDate, EndDate);
public string CalculateDays(DateTime StartDate, DateTime EndDate)
{
DateTime oldDate;
DateTime.TryParse(StartDate.ToShortDateString(), out oldDate);
DateTime currentDate = EndDate;
TimeSpan difference = currentDate.Subtract(oldDate);
// This is to convert the timespan to datetime object
DateTime DateTimeDifferene = DateTime.MinValue + difference;
// Min value is 01/01/0001
// subtract our addition or 1 on all components to get the
//actual date.
int InYears = DateTimeDifferene.Year - 1;
int InMonths = DateTimeDifferene.Month - 1;
int InDays = DateTimeDifferene.Day - 1;
return InYears.ToString() +" Years "+ InMonths.ToString() +" Months " + InDays.ToString() +" Days";
}
在这里可以找到:是一个很好的第三方工具:
FromDays(1).Humanize(precision:2) => "1 day" // no difference when there is only one unit in the provided TimeSpan
TimeSpan.FromDays(16).Humanize(2) => "2 weeks, 2 days"
// the same TimeSpan value with different precision returns different results
TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"
TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"
TimeSpan.FromMilliseconds(1299630020).Humanize(4) => "2 weeks, 1 day, 1 hour, 30 seconds"
TimeSpan.FromMilliseconds(1299630020).Humanize(5) => "2 weeks, 1 day, 1 hour, 30 seconds, 20 milliseconds"
参考:相关:。基本上,
TimeSpan
没有“月”或“年”的概念,因为这需要一些关于时间段的上下文,差异是如何产生的没有内置函数。