Only Bolivian Here
Only Bolivian Here

Reputation: 36723

Formatting a date using C# in an MVC3 application

I have a model with a DateTime property:

public DateTime EndTime { get; set; }

In my controller, I assign that property to a value returned from my database:

aModel.EndTime = auction.EndTime.Value;

And in my View:

<p class="time">@item.EndTime</p>

Currently the date is returned as:

9/12/2011 --> Month / Day / Year

I want it to display as:

12/9/2011 --> Day / Month / Year

I'm sure the application is displaying the date according to the servers settings, but I do not wish to change that. How can I display the date like I want to in the second example?

Upvotes: 2

Views: 2484

Answers (3)

musefan
musefan

Reputation: 48415

The quick and easy way...

<p class="time">@item.EndTime.ToString("dd/MM/yyyy")</p>

I would suggest you store the format string as a config value though so you can easily change it later... or add a way for the user to set their preference

Maybe even do some extension method work...

Helper class

public static class ExtensionMethods
{
   public static string ToClientDate(this DateTime dt)
   {
      string configFormat = System.Configuration.ConfigurationManager.AppSettings["DateFormat"];
      return dt.ToString(configFormat);
   }
}

Config File

<appSettings>
    <add key="DateFormat" value="dd/MM/yyyy" />
</appSettings>

View

<p class="time">@item.EndTime.ToClientDate()</p>

Make sure you View can see the ExtensionMethods class, add a "Using" statement if needed

Upvotes: 2

Blindy
Blindy

Reputation: 67352

Use the ToString method in your view:

<p class="time">@item.EndTime.ToString("d/M/yyyy")</p>

Upvotes: 1

BZink
BZink

Reputation: 7947

<p class="time">@String.Format("{0:dd/MM/yyyy}",item.EndTime)</p>

Upvotes: 3

Related Questions