我有两个日期:
Start Date: 2007-03-24
End Date: 2009-06-26
现在我需要通过以下形式找到这两者之间的区别:
2 years, 3 months and 2 days
如何在c#windows窗体中执行此操作?
答案 0 :(得分:0)
您需要使用TimeSpan
来获得差异..
class Program
{
static void Main(string[] args)
{
string StartDate = "2007-03-24";
string EndDate = "2009-06-26";
System.DateTime firstDate = DateTime.ParseExact(StartDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
System.DateTime secondDate = DateTime.ParseExact(EndDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
System.TimeSpan diff = secondDate.Subtract(firstDate);
var totalDays = (diff).TotalDays;
var totalYears = Math.Truncate(totalDays / 365);
var totalMonths = Math.Truncate((totalDays % 365) / 30);
var remainingDays = Math.Truncate((totalDays % 365) % 30);
Console.WriteLine("Estimated duration is {0} year(s), {1} month(s) and {2} day(s)", totalYears, totalMonths, remainingDays);
Console.ReadLine();
}
}
答案 1 :(得分:-1)
.net已经提供TimeSpan类来显示两个日期时间值之间的差异。TimeSpan类的一些属性分别显示年,月和日间隔