Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a Date or Time section in a DateTime object in C#

Tags:

c#

datetime

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?

like image 362
Ryall Avatar asked Sep 11 '09 14:09

Ryall


2 Answers

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.

like image 194
Jon Skeet Avatar answered Sep 26 '22 07:09

Jon Skeet


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);
}
like image 35
Reed Copsey Avatar answered Sep 26 '22 07:09

Reed Copsey