在C#中比较AM和PM

时间:2017-09-24 11:20:17

标签: c# datetime compare

我比较时间。请参阅我有此代码

            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部分它不起作用,我不知道为什么。从StarNightCleaning一直到EndNight。有什么想法吗?这是我在比较部分的代码

            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;
            }

1 个答案:

答案 0 :(得分:0)

使用Hour属性并尝试将逻辑简化为数字。

var test=[{ID: "91",Name: "sgtue", standardID: "1"},
{ID: "41",Name: "asdfasdf", standardID: "2"},
{ID: "5", Name: "credd", standardID: "2"},
{ID: "2",Name: "dddawer", standardID: "2"},
{ID: "2",Name: "dsfadf", standardID: "3"},
{ID: "275", Name: "xcvcvc", standardID: "201"}
];