2016-11-28 33 views
1

請告訴我如何檢查當前日期(DateTime.Now)是否符合格式爲「dd/mm」的日期格式。例如 - 01.01 <= DateTime.Now <= 01.03 - 當前日期多於1st of January但小於1st of March如何使用DateTime.Now格式「dd/mm」比較日期

+0

您必須將兩者都轉換爲日期和檢查。 – Prajwal

+0

所以如果DateTime.Now是3月1日23:59你期望你的範圍評估爲真?如果是,那麼下面的答案是不正確的。 – Mick

+0

[Diapason](http://www.merriam-webster.com/dictionary/diapason)? –

回答

2

dateStrFrom是第一輸入即開始日期和dateStrTo是第二個輸入即是最新的。然後您可以使用DateTime.TryParseExact將其轉換爲所需的DateTime對象以處理您的比較。

我希望您正在尋找這樣的事情:

string dateStrFrom = "01.01"; 
string dateStrTo = "01.03"; 
DateTime dateFrom, dateTo; 
DateTime.TryParseExact(dateStrFrom, "dd.MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateFrom); 
DateTime.TryParseExact(dateStrTo, "dd.MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTo); 
if (dateFrom <= DateTime.Now && dateTo <= DateTime.Now) 
{ 
    // code here this will be the true condition for you 
} 
+0

可能不是他期待的結果,這將不匹配2月28日午夜後的任何事情 – Mick

1

試試這個:

DateTime.Compare(DateTime.Now, DateTime.ParseExact("01.03", "dd.MM", null)) 

這將返回有符號數指明T1和t2.Value類型條件較少的相對值大於零T1是早於t2。零點t1與t2相同。大於零的t1比t2晚。

+0

謝謝,但需要檢查diapason – Fullbalanced

1
 DateTime dt1 = DateTime.ParseExact("01/01", "dd/MM",null); 
     DateTime dt2 = DateTime.ParseExact("28/11", "dd/MM", null); 

     if (dt1 <= DateTime.Now && DateTime.Now < dt2) 
     { 
      MessageBox.Show("hi"); 
     } 

,如果有人找到解決方案,謝謝

0

可以使用DateTime.Parse解析()。對於你的情況,你可以使用DateTime.Compare()

示例代碼將幫助你。

// If you want to compare only date part of DateTime, not time part: 
DateTime d1 = DateTime.Parse("10/11/2016"); 
DateTime d2 = DateTime.Parse("01/01/2016"); 

if (d1.Date > d2.Date) 
{ 
    // do the stuff 
} 
// For Converting it to String 
DateTime.Now.ToString("MM/dd/yyyy"); 
DateTime.Today.ToString("MM/dd/yyyy"); 


// Comparison 
int result = DateTime.Compare(today, otherdate); 
if(result < 0) 
MessageBox.Show("Today is earlier than the 'otherdate'"); 
elseif(result > 0) 
MessageBox.Show("Today is later than the 'other date'"); 
else 
MessageBox.Show("Dates are equal..."); 

// Will give you a DateTime typed object 
var dateTime = DateTime.Parse("01/01/2016");