2010-02-02 98 views
0

我有一個名爲date的字符串。 date保留日期,如jan 10。我想檢查它是否在兩個日期之間。示例jan 10介於dec 10feb 10之間。我該怎麼做這個任務?日期比較問題

+0

能否請您使用大寫字母,在句子和專有名詞的開始? – 2010-02-02 12:26:03

+0

三個日期都是字符串嗎? – zapping 2010-02-02 12:31:37

回答

0

馬尼什

這應該,如果你使用的是C#

public bool IsDateBetweenOtherDates(DateTime startDate,DateTime endDate, DateTime testDate) 
    { 
     return startDate < testDate && endDate > testDate; 
    } 
+0

你也可以使用擴展方法。 – 2010-02-02 12:32:51

0
string date = "jan 10"; 
var dt = DateTime.ParseExact(date, "MMM dd", CultureInfo.InvariantCulture); 
if (dt < new DateTime(dt.Year, 12, 10) && 
    dt > new DateTime(dt.Year, 2, 10)) 
{ 
    // the date is between 10 feb and 10 dec. 
} 
+0

你的第一次演出日期並不完全正確。它會將它投射到與他約會的同一年。您需要dt.Year - 1 – 2010-02-02 12:36:16

+0

鑑於輸入沒有年份組件,'ParseExact'方法將使用當前年份,如果使用'dt.Year - 1',則條件將永遠不會**。 – 2010-02-02 12:42:10

0

您需要使用DateTime.TryParse()把你的字符串轉換成一個DateTime,那麼它可以比其他日期做。

DateTime minDate = // minimum boundary 
DateTime maxDate = // maximum boundary 
string input = "January 10, 2010"; 
DateTime inputDate; 
if (DateTime.TryParse(input, out inputDate)) 
{ 
    if (inputDate > minDate && inputDate < maxDate) 
    { 
     ... 
    } 
} 
1

將您的日期轉換爲DateTime並使用JPLabs extension method Between

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace JpLabs.Extensions 
{ 
    public static class ComparableExt 
    { 
     static public bool Between<T>(this T actual, T lower, T upper) where T : IComparable<T> 
     { 
      return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) < 0; 
     } 
    } 
} 

我希望它有幫助。

-1

試試這個:

public bool IsDateBetweenOtherDates(DateTime startDate,DateTime endDate, DateTime testDate) 
    { 
     return startDate < testDate && endDate > testDate; 
    } 
+0

考慮解釋爲什麼這個代碼應該工作。這使得答案對其他人更有用,並且更有可能被讚賞。 – Kris 2014-09-02 07:56:12