我是編程新手。運營商無法應用
var time = DateTime.Now.ToShortTimeString().ToString();
var timePattern = "09:30";
if (time.ToString() <= timePattern.ToString())
{
//disable the button
}
錯誤顯示:操作員「< =」不能應用於類型「串」和「串」的操作數
任何人可以幫助我寫這行代碼時,我得到的錯誤?
我是編程新手。運營商無法應用
var time = DateTime.Now.ToShortTimeString().ToString();
var timePattern = "09:30";
if (time.ToString() <= timePattern.ToString())
{
//disable the button
}
錯誤顯示:操作員「< =」不能應用於類型「串」和「串」的操作數
任何人可以幫助我寫這行代碼時,我得到的錯誤?
您不能應用小於等於(<=
)的運算符來鍵入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
}
< =運算符沒有爲字符串的值定義。 而應該讓你在比較DateTime的情況而言
看看這個:http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx
不要把DateTime是否爲字符串對它們進行比較,直接使用DateTime是否。
爲了把字符串轉換成一個DateTime,使用DateTime.Parse或DateTime.ParseExact
注意
比較字符串:
使用String.Compare
到compare字符串這樣。
<=
尚未實施字符串。
您應該直接比較DateTime
s,而不是將它們轉換爲字符串。該<=
operator has been implemented爲DateTime
所以它應該是那麼容易,因爲:
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對它進行排序。
你可以做到這一點,而無需指定年/月/日...
if (DateTime.Now.TimeOfDay < new TimeSpan(9, 30, 0))
{
// ... it's before 9:30 am ...
}
使用''==而不是'<=' – Xaqron 2013-05-02 04:20:51
okay..i'll嘗試另一種選擇1號..感謝 – azfar 2013-05-02 04:29:21