2013-05-02 36 views
0

我是編程新手。運營商無法應用

var time = DateTime.Now.ToShortTimeString().ToString(); 
var timePattern = "09:30"; 
      if (time.ToString() <= timePattern.ToString()) 
{ 
//disable the button 
} 

錯誤顯示:操作員「< =」不能應用於類型「串」和「串」的操作數

任何人可以幫助我寫這行代碼時,我得到的錯誤?

+1

使用''==而不是'<=' – Xaqron 2013-05-02 04:20:51

+0

okay..i'll嘗試另一種選擇1號..感謝 – azfar 2013-05-02 04:29:21

回答

2

您不能應用小於等於(<=)的運算符來鍵入string

看起來你正試圖檢查當前時間是否小於9:30。爲此,請比較DateTime實例。

DateTime currentTime = DateTime.Now; 
//Creates a DateTime instance with the current year, month, day at 9:30AM 
DateTime nineThirty = 
    new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 9, 30, 0); 
if(currentTime.TimeOfDay <= nineThirty.TimeOfDay) 
{ 
    //your code 
} 
+0

謝謝..我嘗試第一或者工作或不..謝謝 – azfar 2013-05-02 04:29:48

+0

還有一個想..我試圖通過寫這個做timer.so,我不需要使用計時器嗎? – azfar 2013-05-02 04:32:07

+0

謝謝..工作.. :) – azfar 2013-05-02 05:53:27

0

不要把DateTime是否爲字符串對它們進行比較,直接使用DateTime是否。

爲了把字符串轉換成一個DateTime,使用DateTime.Parse或DateTime.ParseExact

注意

比較字符串:

使用String.Comparecompare字符串這樣。

<=尚未實施字符串。

0

您應該直接比較DateTime s,而不是將它們轉換爲字符串。該<= operator has been implementedDateTime所以它應該是那麼容易,因爲:

var time = DateTime.Now; 
var timePattern = new DateTime(time.Year, time.Month, time.Day, 9, 30, 0); 
if (time <= timePattern) 
{ 
    //disable the button 
} 

僅供參考,你不能字符串使用<=,你將需要使用string.CompareTo代替。

if (time.ToString().CompareTo(timeParrent.ToString()) <= 0) 

還是static方法string.Compare一種替代語法。

if (string.Compare(time.ToString(), timeParrent.ToString()) <= 0) 

而且DateTime.ToShortTimeString()不會放棄的排序(在所有情況下)格式的格式。您可以使用time.ToString("u")使用可排序的日期/時間模式格式將日期作爲字符串獲取。一個你想要做的例子就是將日期打印到HTML中並用JavaScript對它進行排序。

1

你可以做到這一點,而無需指定年/月/日...

 if (DateTime.Now.TimeOfDay < new TimeSpan(9, 30, 0)) 
     { 
      // ... it's before 9:30 am ... 
     }