2017-08-29 69 views
0

我在這裏有一個函數,如果當前時間在兩個軍事時間之間,則試圖返回true。如果當前時間介於兩個軍事時間之間,則返回true?

這裏的問題是找到21300700之間的時間有點棘手。 2130工作正常,但07002130之前,所以它在這裏返回false。我怎樣才能讓這個返回true?

只需將&&切換爲||

public bool IsSleeping() 
{ 
    DateTime m_dt = DateTime.Now; 
    string strMilitaryTime; 
    int time; 

    strMilitaryTime = m_dt.ToString("HHmm"); // Get current military time 
    time = Convert.ToInt32(strMilitaryTime); // Convert to int 

    // The time must be between sleeping hours of 2400 and 0700. 
    if (time >= 2130 && time < 700) 
     return true; 

    return false; 
} 
+1

「軍事時間」是不是一個東西(或至少,這是一個非常美洲爲中心的術語)。我想你的意思是24小時製表示法,但什麼時區? – Dai

+0

*只需將'&&'切換爲'||'*請嘗試看看。你也可以:'return(time> = 2130 && time <700)' –

+0

使用整數並不理想,用'TimeSpan'來表示時間值。 – Dai

回答

2
public static Boolean IsSleeping() 
{ 
    TimeSpan now = DateTime.Now.TimeOfDay; 

    TimeSpan before = new TimeSpan( 7, 0, 0); 
    TimeSpan after = new TimeSpan(21, 30, 0); 

    return now < before || now > after; 
} 
+0

請不要轉儲「固定」代碼,解釋您的方法以及爲何解決問題。 – CodeCaster

+0

這對我來說非常可讀。謝謝!儘管我想知道TimeOfDay是否返回24小時時間,但MSDN可能會回答這個問題。 – Phil

相關問題