Reputation: 7112
I have 2 datetime objects that I need to combine.
This contains the correct date, but the time part is not needed.
DateTime? sessionDate = fl.EventDateTimeStart
This contains the correct time, but the date part needs to be the date value from the sessionDate object above.
DateTime? sessionStartTime = g.GameStartTime.Value
I tried using some of the various DateTime toString() methods, but found out that because they are part of a class, they need to remain DateTime? types so I can't just convert them to a string.
So I came up with this really ugly method:
sessionStartTime = new DateTime(
fl.EventDateTimeStart.Value.Year,
fl.EventDateTimeStart.Value.Month,
fl.EventDateTimeStart.Value.Day,
g.GameStartTime.Value.Hour,
g.GameStartTime.Value.Minute,
g.GameStartTime.Value.Second)
Is there a more elegant way of to do this?
Thanks!
Upvotes: 0
Views: 83
Reputation: 42300
Sure.
var result = fl.Value.Date + g.Value.TimeOfDay;
DateTime.Date
returns a DateTime
with the time part set to midnight. DateTime.TimeOfDay
gets a TimeSpan
containing the fraction of the day that has elapsed since midnight.
Make sure that both of your DateTimes
have the same Kind
, otherwise the result might not be what you expect.
Upvotes: 4