比较C#中的AM和PM



im比较时间。看到我有这个代码

            DateTime t1 = DateTime.Now;
            DateTime StartMorningCleaning = Convert.ToDateTime("6:00:00 AM");
            DateTime EndMorningCleaning = Convert.ToDateTime("6:59:59 AM");
            DateTime StartMorning = Convert.ToDateTime("7:00:00 AM");
            DateTime EndMorning = Convert.ToDateTime("6:59:59 PM");
            DateTime StartNightCleaning = Convert.ToDateTime("7:00:00 PM");
            DateTime EndNightCleaning = Convert.ToDateTime("7:59:59 PM");
            DateTime StartNight = Convert.ToDateTime("8:00:00 PM");
            DateTime BeforeMidnight = Convert.ToDateTime("11:59:59 PM");
            DateTime Midnight = Convert.ToDateTime("12:00:00 AM");
            DateTime EndNight = Convert.ToDateTime("5:59:59 AM");

如果在开始时间和结束时间之间,则试图比较当前时间。问题是当我去PM部分时,它不起作用,我不知道为什么。从starnight clean凝结到末日。有什么想法吗?这是我在比较部分中的代码

            if (t1 >= StartMorningCleaning && t1 <= EndMorningCleaning)
            {
                MessageBox.Show("Morning Cleaning Time");
                CleaningTime = false;
            }
            else if (t1 >= StartMorning && t1 <= EndMorning)
            {
                MessageBox.Show("MorningTour");
                CleaningTime = true;
            }
            else if (t1 >= StartNightCleaning && t1 <= EndNightCleaning)
            {
                MessageBox.Show("Night Cleaning Time");
                CleaningTime = false;
            }
            else if (t1 >= StartNight && t1 <= BeforeMidnight)
            {
                MessageBox.Show("NightTour");
                CleaningTime = true;
            }
            else if (t1 >= Midnight && t1 <= EndNight)
            {
                MessageBox.Show("NightTour");
                CleaningTime = true;
            }

使用小时属性并尝试将逻辑减少到数字。

int t1 = DateTime.Now.Hour;             
if (t1 >= 6 && t1 < 7) {
    MessageBox.Show("Morning Cleaning Time");
    CleaningTime = false;
} else if (t1 >= 7 t1 < 19) {
    MessageBox.Show("MorningTour");
    CleaningTime = true;
} else if (t1 >= 19 && t1 < 20) {       //PM
    MessageBox.Show("Night Cleaning Time");
    CleaningTime = false;
} else if (t1 >= 20 && t1 <= 23) {      //PM
    MessageBox.Show("NightTour");
    CleaningTime = true;
} else if (t1 >= 0 && t1 <= 5) {       //AM - this if can be just else (remove if part)
    MessageBox.Show("NightTour");
    CleaningTime = true;
}

相关内容

  • 没有找到相关文章

最新更新