2

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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

From memory (and other answers) that should be MM rather than mm I think.
Yeah. You're right. just changed it. Was trying to get the answer in too quickly! ha.
I mainly noticed because I once deployed production code with mm instead of MM and ever since then I've been hyper-aware. ;-)
2

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

Comments

1

Use the ToString method in your view:

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

1 Comment

That simple huh. Man C# is fantastic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.