Reputation: 1348
I have a series of datetimes of which I need to flatten the Date potion and only keep time values.
Note: The reason behind to do such a weird thing is that we use a third party component that uses Date Part to make certain decisions. Also, I found a different way to get around it but I am still curious if there's a more efficient way to achieve this.
The only way I could think is create new DateTime objects with the same date but with times from individual source DT objects.
This is a simple example of the approach that I don't like at all.
DateTime flattenDts(DateTime input)
{
return new DateTime(1, 1, 1, input.Hour, input.Minute, input.Second);
}
as you can see, this doesn't look very good at all. specially when there are hundreds of datetime values.
Is there a more efficient way to achieve this?
Edit: Please note that I cannot use timespan as the third party lib. will only take DateTime parameters.
Upvotes: 1
Views: 401
Reputation: 205769
I think a little bit more efficient would be to use the construct
new DateTime(input.TimeOfDay.Ticks)
For easy usage (and also changing the implementation if needed), put that inside an extension method as @Matthew Watson suggested. I would call it TruncateDate
, but that's not essential.
Upvotes: 1
Reputation: 109792
There's no more efficient way to do this, but you could reduce the amount of typing you need to do by writing an extension method to do it:
public static class DateTimeExt
{
public static DateTime Flatten(this DateTime self)
{
return new DateTime(1, 1, 1, self.Hour, self.Minute, self.Second);
}
}
Then code to flatten the date would look like this:
DateTime test = DateTime.Now;
var flattened = test.Flatten();
It's not much, but perhaps it will help a little.
Upvotes: 5
Reputation: 17605
According to the documentation of DateTime
, the properties are read-only. This means that basically DateTime
is immutable; if a modification of the contents is desired, this is only possible with a new object. In short, there is no solution which is more efficient.
Upvotes: 1