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?
Place the text cursor where you want to insert the date and time. Click the Insert tab in the Ribbon. On the Insert tab, click the Date & Time option. Select the date or time format you want to insert in the document.
var dateValue = new Date("2021-01-12 10:10:20"); Use new Date() along with setHours() and getHours() to add time.
MinValue defines the date and time that is assigned to an uninitialized DateTime variable. The following example illustrates this. C# Copy.
The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance's date and time and Coordinated Universal Time (UTC).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With