Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join Date and Time to DateTime in C#

Tags:

c#

datetime

I am retrieving data from an iSeries where there is a separate date and time fields. I want to join them into a DateTime field in my C# project. I don't see a way to add just a time to a DateTime field. How would you suggest accomplishing this?

like image 806
Mike Wills Avatar asked Jun 29 '10 16:06

Mike Wills


4 Answers

You can do this quite easily:

DateTime dateOnly;
DateTime timeOnly;
...
DateTime combined = dateOnly.Date.Add(timeOnly.TimeOfDay);

TimeOfDay returns a TimeSpan, which you then add to the date.

Edit (thanks to commenters below) - to be safe, use dateOnly.Date to ensure the date part only.

like image 188
David M Avatar answered Nov 18 '22 11:11

David M


How are they being stored? Assuming that the date portion is being stored as a DateTime of midnight of the day in question and the time is a TimeSpan, you can just add them.

DateTime date = ...;
TimeSpan time = ...;

DateTime result = date + time;
like image 27
Adam Robinson Avatar answered Nov 18 '22 09:11

Adam Robinson


You could easily construct a TimeSpan from your "time" field.

Once you have that, just do:

TimeSpan time = GetTimeFieldData();
dateField = dateField.Add(time);
like image 8
Reed Copsey Avatar answered Nov 18 '22 10:11

Reed Copsey


Datetime date = new DateTime(Date1.Year, Date1.Month, Date1.Day, Time1.Hour, Time1.Minute, Time1.Second); 
like image 4
Mark Dykun Avatar answered Nov 18 '22 09:11

Mark Dykun