Adding a Time to a DateTime in C#

后端 未结 6 1832
执笔经年
执笔经年 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:40

    If you are using two DateTime objects, one to store the date the other the time, you could 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

    0 讨论(0)
  • 2020-12-05 06:44

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

    DateTime dateTime = DateTime.Now;
    DateTime combined = dateTime + 36.Hours();
    Console.WriteLine(combined);
    
    0 讨论(0)
  • 2020-12-05 06:49
       DateTime newDateTime = dtReceived.Value.Date.Add(TimeSpan.Parse(dtReceivedTime.Value.ToShortTimeString()));
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-05 06:55

    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:ffffdd}", 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.

    0 讨论(0)
  • 2020-12-05 06:58

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

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

    0 讨论(0)
提交回复
热议问题