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?
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);
}
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.
This may not be exactly what you're looking for, but the DateTime class has a series of Add methods (AddMinutes(), AddDays(), etc.). I say this might not be what you're looking for, because these return a DateTime, so you would have to do something like
myDate = myDate.AddMinutes(60);
Strip the time from an existing datetime by writing .Date
DateTime new = oldDate.Date;
Add your TIme by either adding the hours, minutes & seconds individually
DateTime new = oldDate.Date.AddHours(14).AddMinutes(12).AddSeconds(33);
or all at once
DateTime new = oldDate.Date.AddSeconds(51153);
or by adding a TimeSpan()
DateTime new = oldDate.Date.Add(new TimeSpan(14,12,33));
@Reed Copsey: Your solution is really fantastic.... It really worked out.