0

我想知道如何DateTime.Now以相同的格式进行格式化Thursday 03:00 PM,以便将其与我的自定义格式日期时间值进行比较,

我正在尝试创建一个简单的调度系统,如果特定日期时间与当前日期时间相等,则代码将在其下运行,但我坚持将自定义日期与当前日期时间进行比较

string[] schedule = { "Thursday 2:47 PM", "Thursday 2:50 PM", "Thursday 2:55 PM" };
        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime dateValue;
            foreach (var i in schedule)
            {
                if (DateTime.TryParse(i, out dateValue))
                {
                    if (dateValue == DateTime.Now)
                    {
                        //do something here
                    }
                }
            }
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            timer1.Start();
        }
4

6 回答 6

3

尝试dateValue.ToString("dddd hh:mm tt", CultureInfo.CreateSpecificCulture("en-US"))

  • dddd - 星期几的全名。
  • hh - 小时,使用从 01 到 12 的 12 小时制。
  • mm - 分钟,从 00 到 59。
  • tt - AM/PM 指示符。

您可以参考MSDN了解更多信息。

于 2013-04-11T07:09:32.837 回答
2

它应该以这种方式工作。

if (DateTime.TryParse(i, out dateValue))
{
  if (dateValue.ToShortTimeString() == DateTime.ToString("dd hh:mm tt"))
  {
    //do something here
  }
}

dd告诉显示当前日期。hh显示小时,mm显示分钟。我离开ss几秒钟,因为您似乎不需要它。通过tt PMAM将得到显示。

于 2013-04-11T07:14:05.667 回答
1

First, you need to convert time in schedule string array into DateTime.

Link about DateTime styles: http://www.csharp-examples.net/string-format-datetime/

After that, you need to compare only time part of 2 dates. Took the answer from here: How to compare time part of datetime

So, finally your code will be something like this:

string[] schedule = { "Thursday 2:47 PM", "Thursday 2:50 PM", "Thursday 2:55 PM" };
private void timer1_Tick(object sender, EventArgs e)
{
    DateTime dateValue;
    foreach (var i in schedule)
    {
        if (DateTime.TryParseExact(i, "dddd h:mm tt", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out dateValue))
        {
            var currentDate = DateTime.Now;
            if (dateValue.DayOfWeek == currentDate.DayOfWeek && dateValue.TimeOfDay == currentDate.TimeOfDay)
            {
                //do something here
            }
        }
    }
}

private void Form1_Shown(object sender, EventArgs e)
{
    timer1.Start();
}

Of course, you can convert DateTime.Now to a string of valid format (as in your string array) but I think that it's wrong. If you want to check that your date is earlier or later than current date, you will have to rewrite your code.

于 2013-04-11T07:28:08.860 回答
1

您正在尝试将Time价值与DateTime价值进行比较。我认为您只想将您array的时间值与current时间值进行比较,在这种情况下,您可以比较日期的时间部分。

if (DateTime.TryParse(i, out dateValue))
{
  if (dateValue.ToShortTimeString() == DateTime.Now.ToShortTimeString())
  {
    //do something here
  }
}
于 2013-04-11T07:11:21.457 回答
1

请在此处查看日期时间示例日期时间格式

例如

MyString = MyDateTime.ToString("dddd  hh:mm tt");
于 2013-04-11T07:11:31.413 回答
1

使用DateTime.ParseExact方法将字符串从自定义格式转换为 DateTime

于 2013-04-11T07:05:45.240 回答