爲了更清楚地瞭解:你不想來比較兩個日期(或DateTime是否)但兩個TimeSpans。即現在的與您提供的日期之間的時間差異爲,並且時間跨度爲12個月。
String d = "26/06/10";
DateTime dt = DateTime.ParseExact(d, "dd/MM/yy", CultureInfo.InvariantCulture);
TimeSpan deltaTimeSpan = dt - DateTime.Now; // get the time difference between now and the time given
TimeSpan twelveMonths = new TimeSpan(365,0,0,0); // get a time span of 12 months
// round the amount of days down and always supply a positive number of days
int deltaTime = Convert.ToInt32(Math.Abs(Math.Floor(deltaTimeSpan.TotalDays)));
if (twelveMonths.TotalDays > deltaTime)
{
Console.WriteLine(string.Format("It is less than 12 months ({0} days).", deltaTime));
}
else if (twelveMonths.TotalDays < deltaTime)
{
Console.WriteLine(string.Format("It is more than 12 months ({0} days).", deltaTime));
}
else
{
Console.WriteLine(string.Format("The difference in time is exactly 12 months. ({0} days).", deltaTime);
}
請注意,這個例子當然不考慮閏年。代碼確實考慮了一年中的天氣與過去或未來的謊言進行比較(通過將TimeSpan轉換爲正值並與該值進行比較)。
調整上述代碼在兩週或任何其他時間範圍內執行相同操作應該足夠簡單。只要改變我命名爲「十二個月」的TimeSpan即可。
我認爲你現在正在做的是最好的方法。 – Magnus