2016-10-03 35 views
0

爲什麼我不能在字符串格式爲textboxordertostart.Text的時間等於系統時間時播放此音頻文件? TextboxordertostartDateTimePicker時間減去分鐘後得到時間。如果時間匹配播放音頻文件

我的代碼如下。

SoundPlayer myplayer = new SoundPlayer(); 

myplayer.SoundLocation= (@"c:\users\woolsvalley\documents\visual studio 2015\Projects\WindowsFormsApplication17\WindowsFormsApplication17\Alarm.wav"); 


if (DateTime.Now.ToString("hh:mm tt") == textBox_ordertostart.Text) 
{ 
    myplayer.Play(); 
} 

該代碼會引發空異常

string formatString = "yyyHHmmss"; 
     string sample = textBox_ordertostart.Text; 
     DateTime dt = DateTime.ParseExact(sample, formatString, null); 
     if (DateTime.Now == dt) 
     { myplayer.Play(); } 

這是行不通的,以及

if (DateTime.Now == DateTime.Parse(textBox_ordertostart.Text)) 
     { myplayer.Play(); } 
+2

「textBox_ordertostart.Text」的值是什麼?您是否已經在調試器中逐步瞭解代碼? – Tim

+1

我會在條件行上設置一個斷點,然後手動檢查'DateTime.Now.ToString(「hh:mm tt」)'返回的結果。您應該能夠將其與您在文本框中輸入的值進行比較,並輕鬆瞭解它們不匹配的原因。 –

+0

你的'textBox_ordertostart.Text'是否會返回一個類似於這個'00:00 PM'的值? –

回答

2

你做比較的方式是這樣做的一個非常「脆」的方式比較是因爲它取決於用戶輸入的時間格式與你期望的格式相符。例如,當我測試這個時,我得到了以下結果:

string datetime = DateTime.Now.ToString("hh:mm tt"); 

// False 
Console.WriteLine(datetime == "2:06 PM"); 

     // False 
     Console.WriteLine(datetime == "2:06 P.M."); 
     // False 
     Console.WriteLine(datetime == "2:06"); 

     // False 
     Console.WriteLine(datetime == "02:06 P.M."); 

     // True 
     Console.WriteLine(datetime == "02:06 PM"); 

如果你解析它到一個DateTime對象,然後做ToString,但它會更脆弱。看到這個擴展方法,例如:

public static bool DayMinuteEqual(this string otherDate) 
    { 
     // We have to strip out the "." character if present (e.g. 2:05 P.M.) 
     DateTime otherDateObj = DateTime.Parse(otherDate.Replace(".", "")); 

     return DateTime.Now.ToString("hh:mm tt") == otherDateObj.ToString("hh:mm tt"); 
    } 

現在,我得到我預期的結果:

// True 
     Console.WriteLine("2:20 PM".DayMinuteEqual()); 

     // True 
     Console.WriteLine("2:20 P.M.".DayMinuteEqual()); 

     // False, but we'd expect it due to the omission of the "P.M." 
     Console.WriteLine("2:20".DayMinuteEqual()); 

     // True 
     Console.WriteLine("02:20 P.M.".DayMinuteEqual()); 

     // True 
     Console.WriteLine("02:20 PM".DayMinuteEqual()); 

很明顯,那麼,這更依賴於進入一個「完美」的格式顯示用戶(但仍然要求他們有一些意義上的正確格式)。

0

謝謝你們。此代碼的工作原理我只需要在更新事件中引發它。

private void timer1_Tick(object sender, EventArgs e) 
    { label_time1.Text = DateTime.Now.ToString("hh:mm tt"); 
     mplayer = new SoundPlayer(); 
     mplayer.SoundLocation = (@"c:\users\woolsvalley\documents\visual studio 2015\Projects\WindowsFormsApplication17\WindowsFormsApplication17\Alarm.wav"); 
     if((DateTime.Now.ToString("HH:mm tt") == ((textBox_ordertostart.Text)))) 
     { mplayer.Play(); }