Reputation: 3555
I'm using c# mvc4. Every entity with create date member I'm saving DateTime in my DB as DateTime.UtcNow, I have many views to show entities and in my html: @item.Created repeated many times. I want that the default ToString() will be ToLocalTime, is there a one place were I can declare this ? maybe override the default ToString()
Upvotes: 1
Views: 553
Reputation: 241563
No, you cannot override .ToString()
on a DateTime
.
DateTime
is a struct, not a class. And it's sealed.
An extension method is a good idea, but it will not be called automatically. You must call it when you need it.
You said you just wanted a single place to change the behavior of DateTime.ToString()
globally. There is no way to do that, and it would probably be dangerous to do so. After all, you're using UTC values for a reason. If you want local values, then use local values.
The only way I can even think you might be able to achieve this is with some post-build step, such as are commonly done in AOP frameworks like PostSharp. You could write an aspect that does the conversion. But again, I strongly recommend against this idea in general.
Upvotes: 0
Reputation: 23937
Yes of course you can override the ToString() method.
See http://msdn.microsoft.com/en-us/library/ms173154(v=vs.80).aspx for further reference.
However - I recommend using an Extension Method to realize your need, because you could use the default ToString() extension in another place.
/Update: Using an extension method allowing the datetime to be a null value (something always goes wrong). You can call this on every DateTime value. The method then checks if it is null. In this case it returns a string.empty, else the Datetime in a format you like.
public static string ToLocalString(this DateTime? date)
{
if(date == null)
{
return String.Empty;
}
else
{
return date.ToLocalString().ToString();
}
}
Upvotes: 3
Reputation: 5398
I agree with the Serv's answer that you shouldn't override default .ToString() for DateTime and better use extension method. Just wanted to add that you have option to use Property getter like this:
private DateTime _created;
public DateTime Created
{
get {
return _created.ToLocalTime();
}
}
But in my opinion - extension method would be the best option.
Upvotes: 1