Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Time to a DateTime in C#

Tags:

c#

datetime

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?

like image 644
4imble Avatar asked Jan 27 '10 11:01

4imble


People also ask

How do you add time to a date?

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.

How do I add time to a date string?

var dateValue = new Date("2021-01-12 10:10:20"); Use new Date() along with setHours() and getHours() to add time.

What is DateTime MinValue in C#?

MinValue defines the date and time that is assigned to an uninitialized DateTime variable. The following example illustrates this. C# Copy.

What is DateTimeOffset C#?

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


2 Answers

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.

like image 151
Simon P Stevens Avatar answered Oct 14 '22 11:10

Simon P Stevens


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

like image 28
user3258819 Avatar answered Oct 14 '22 11:10

user3258819