Adding time in DateTime in C #

I have a calendar and a text box that contains the time of day. I want to create a date-time that is a combination of the two. I know that I can do this by looking at the clock and coins and then adding them to the DateTime calendar, but that seems pretty dirty.

Is there a better way?

+41
c # datetime
Jan 27 '10 at 11:08
source share
6 answers

You can use the DateTime.Add () method to add 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 own time span for parsing the string if that is what you need to do.

Alternatively, you can use other controls. You did not mention whether you use winforms, wpf or asp.net, but there are various date and time pickers that support date and time pickers.

+73
Jan 27 '10 at 11:10
source share

If you use two DateTime objects, one to save the date of the other, you can do the following:

 var date = new DateTime(2016,6,28); var time = new DateTime(1,1,1,13,13,13); var combinedDateTime = date.AddTicks(time.TimeOfDay.Ticks); 

An example of this can be found here.

+6
Jul 06 '15 at 18:00
source share

Depending on how you format (and check!) The date entered in the text box, 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 format "hh: mm" (optional seconds).

+3
Jan 27 '10 at 11:23
source share

Using https://github.com/FluentDateTime/FluentDateTime

 DateTime dateTime = DateTime.Now; DateTime combined = dateTime + 36.Hours(); Console.WriteLine(combined); 
+3
Jan 28 '10 at 9:53 on
source share

Combine both. The date picker also supports pick time.

You just need to change the Format-Property and possibly the CustomFormat-Property.

0
Jan 27 '10 at 11:11
source share
  DateTime newDateTime = dtReceived.Value.Date.Add(TimeSpan.Parse(dtReceivedTime.Value.ToShortTimeString())); 
0
Jun 28 '17 at 9:38 on
source share



All Articles