I use many DateTime in my code. I want to change those DateTimes to my specific date and keep time.
1. "2012/02/02 06:00:00" => "2015/12/12 : 06:00:00"
2. "2013/02/02 12:00:00" => "2015/12/12 : 12:00:00"
I use this style to change, but it seem not the good way and I want to ask have any way to achieve this task.
DateTime newDateTime = new DateTime(2015,12,12,oldDateTime.Hour,oldDateTime.Minute,0);
A better way that preserves the seconds, milliseconds and smaller parts of the time would be:
DateTime newDateTime = new DateTime(2015,12,12) + oldDateTime.TimeOfDay;
Or you could make an extension method to apply a new Date to an existing DateTime and, at the same time, not trust the new date to be without a TimeOfDay on it:-
public static DateTime WithDate (this DateTime datetime, DateTime newDate)
{
return newDate.Date + datetime.TimeOfDay;
}
IMHO DateTime
is one of the weakest parts of .NET. For example, a TimeSpan
is not the same as a TimeOfDay
nor can it represent a 'TimePeriod' (in months) - these are three separate concepts and mixing them up was a poor choice. Moving to DateTimeOffset
is generally preferred or to the excellent Noda time library.
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