Adding a Time to a DateTime in C#

后端 未结 6 1835
执笔经年
执笔经年 2020-12-05 06:32

I have a calendar and a textbox that contains a time of day. I want to create a datetime that is the combination of the two. I know I can do it by looking at the hours and m

6条回答
  •  爱一瞬间的悲伤
    2020-12-05 06:53

    Depending on how you format (and validate!) the date entered in the textbox, you can do this:

    TimeSpan time;
    
    if (TimeSpan.TryParse(textboxTime.Text, out time))
    {
       // calendarDate is the DateTime value of the calendar control
       calendarDate = calendarDate.Add(time);
    }
    else
    {
       // notify user about wrong date format
    }
    

    Note that TimeSpan.TryParse expects the string to be in the 'hh:mm' format (optional seconds).

提交回复
热议问题