tags:

views:

123

answers:

4

Hi all,

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 mintues and then adding these to the calendar DateTime but this seems rather messy.

Is there a better way?

Thanks, Kohan.

+3  A: 

You can use the DateTime.Add() method to add the time to the date.

DateTime date = DateTime.Now;
TimeSpan time = new TimeSpan(36, 0, 0, 0);
DateTime combined = date.Add(time);
Console.WriteLine("{0:dddd}", combined);

You can also create your timespan by parsing a String, if that is what you need to do.

Alternatively, you could look at using other controls. You didn't mention if you are using winforms, wpf or asp.net, but there are various date and time picker controls that support selection of both date and time.

Simon P Stevens
Did the trick, many thanks.
Kohan
A: 

Combine both. The Date-Time-Picker does support picking time, too.

You just have to change the Format-Property and maybe the CustomFormat-Property.

Bobby
+1  A: 

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).

tomlog
A: 

Using http://www.codeplex.com/fluentdatetime

DateTime dateTime = DateTime.Now;
DateTime combined = dateTime + 36.Hours();
Console.WriteLine(combined);
Simon