Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change only the date portion of a DateTime, while keeping the time portion?

Tags:

c#

datetime

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);
like image 375
borrom Avatar asked Nov 03 '14 03:11

borrom


1 Answers

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.

like image 179
Ian Mercer Avatar answered Oct 06 '22 22:10

Ian Mercer