【问题标题】:How to read from string?如何从字符串中读取?
【发布时间】:2013-04-06 05:10:00
【问题描述】:

我正在尝试学习如何根据用户选择的时间安排图片。

这是有问题的代码:

private void startjob()
{
     string theDate = DateTimePicker1.Value.ToString();
     DateTime dt = Convert.ToDateTime(date);
     {
         DateTime start = new DateTime(2009, 12, 9, 10, 0, 0); //How Do I make this to read the string that is converted from DateTimePicker instead of this?
         DateTime end = new DateTime(2009, 12, 10, 12, 0, 0); //How Do I make this to read the string that is converted from DateTimePicker instead of this?
         DateTime now = DateTime.Now;
         if ((now > start) && (now < end))
         {
         //match found
         }
     }
}

【问题讨论】:

  • 我不明白你想做什么,但DateTimePicker1.ValueDateTime

标签: c# function datetime methods datetimepicker


【解决方案1】:

假设您的控件被命名为 DateTimePicker1 和 DateTimePicker2:

private void startjob()
{
    DateTime start = DateTimePicker1.Value;
    DateTime end = DateTimePicker2.Value;
    DateTime now = DateTime.Now;
    if ((now > start) && (now < end))
    {
    //match found
    }
}

DateTimePicker.Value 属性本身就是一个 DateTime 对象,因此您的代码可以简化,无需转换为字符串。

【讨论】:

  • 感谢您的意见。当我开始写我的答案时,他的答案没有显示出来。我的速度有点慢这一事实是否会降低我的答案的价值?
  • + 1 表示不像 Rohit 那样的娘们。
  • +0:虽然您的回答在技术上是正确的,但并不能解释您的代码为何有效以及原始代码有什么问题。
  • 感谢您的评论。尽管我认为我的代码非常简单,但我已经对其进行了编辑并根据您的评论添加了简短的解释。
【解决方案2】:

DateTimePicker.Value 返回DateTime 对象。您正在尝试不必要地转换为字符串类型和从字符串类型转换。

DateTime start = DateTimePickerStart.Value;
DateTime end = DateTimePickerEnd.Value;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多