Putting two DateTime's together

  • Thread starter Thread starter Michael Groeger
  • Start date Start date
M

Michael Groeger

Hi,

is there a "ideal" way to put two DateTime instances together where the one
DateTime contains the date portion and the other the time portion of the
resulting DateTime?

Regards,
Michael
 
The easiest way I know of is to use the DateTime constructor:

DateTime dt1, dt2, dt3;
dt1 = DateTime.Now;
dt2 = DateTime.Parse("2/16/1992 12:15:12");
dt3 = new DateTime(dt1.Year, dt1.Month, dt1.Day, dt2.Hour, dt2.Minute,
dt2.Second);

- or -

dt3 = new DateTime(dt1.Year, dt1.Month, dt1.Day, dt2.Hour, dt2.Minute,
dt2.Second, dt2.Millisecond);

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
You can lead a fish to a bicycle,
but it takes a very long time,
and the bicycle has to *want* to change.
 
DateTime date = DateTime.Now;
DateTime odate = new DateTime (2006, 1, 1);

DateTime result = new DateTime (odate.Year, odate.Month, odate.Day,
date.Hour, date.Minute, date.Second, date.Millisecond);
 
Hi Kevin,

thanks, I thought there was a better way to do so. :( In the moment I am
doing it this way:

DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Parse("18:00:00");
DateTime dt3 = dt1.Date.Add(dt2.TimeOfDay);

which looks to me more readable.

Regards,
Michael
 
Back
Top