I have a DateTime object which may or may not already contain some date/time information. With that I need to replace the time with my new time independently of the date and vice versa. How would I achieve this? I can't see anything obvious other than creating two new DateTime objects, one with the old/new date and one with the old/new time and concatenating. There surely must be a better way than this?
I would write two or three extension methods:
public static DateTime WithTime(this DateTime date, TimeSpan time)
{
return date.Date + time;
}
public static DateTime WithDate(this DateTime original, DateTime newDate)
{
return newDate.WithTime(original);
}
public static DateTime WithTime(this DateTime original, DateTime newTime)
{
return original.Date + newTime.TimeOfDay;
}
(You really don't need both of the second methods, but occasionally it might be simpler if you're chaining together a lot of calls.)
Note that you aren't creating any objects in terms of items on the heap, as DateTime
is a struct.
DateTime is an immutable structure.
The only option is to construct a new DateTime struct based off your two existing values. This is the best approach. Luckily, it's a one liner:
DateTime CreateNewDateTime(DateTime date, DateTime time)
{
return new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second);
}
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