Chris
Chris

Reputation: 1251

MVC & Date Formatting

Where in an MVC based architecture should the date formatting (long/short/time/no-time/UK/US) live? I want to be able to specify long/short/time/no-time on a per-field basis - i.e. DateOfBirth doesn't care about time, but CreationDate might.

Using ASP.NET MVC, there doesn't seem an easy way to do it in the View, which makes me wonder if it should sit in the ViewModel as a FormattedDate field?

Any suggestions?

Upvotes: 1

Views: 432

Answers (3)

Guidhouse
Guidhouse

Reputation: 1426

I use Htmlhelpers in these situations. This is a primitive one for returning amounts of money formated as preferred in Denmark( guess where I live). I have similar for returning dates and time.

public static class FormatMoneyExtension {
    public static string FormatMoney(this HtmlHelper htmlHelper, decimal? amount) {
        if (null != amount) {
            return ((decimal)amount).ToString("N", System.Globalization.CultureInfo.CreateSpecificCulture("da-DK"));
        } else {
            return new decimal(0.0).ToString("N", System.Globalization.CultureInfo.CreateSpecificCulture("da-DK"));
        }
    }
}

It makes the views much more readable ie:<%:Html.FormatMoney(Model.amount)%>.

You can wrap the native controls, like texbox etc. in a similar way.

Good luck and happy working

Upvotes: 0

Bruno Lopes
Bruno Lopes

Reputation: 3056

I read this as two parts:

  • Formatting (long, short)
  • Data type (date and time, just date, just time)

The first part is a view concern, mostly, and should live in the presentation. I'd most likely just craft some extension methods for the DateTime/Date/Time that include the required translation or perhaps even create presentation versions of the types.

The second part are model concerns, since a date of birth (usually) doesn't include time, regardless of the way you present it, and a starting time for a recurring lecture shouldn't have a date (since it's recurring, it would actually have a start/end). Sadly .net doesn't include (as far as I can recall) separate objects for Date and Time, so I roll my own, usually.

Upvotes: 0

AnthonyWJones
AnthonyWJones

Reputation: 189439

First of all there is a difference between (1:long/short), (2:time/no-time) and (3:UK/US). 1. is definitely a view choice to make, 2. Effectively describes to data types ("DateTime", "Date" (which doesn't exist and you'd need to create)) and 3. is user profile thing, which again belongs in the view.

So far then you only have two types DateTime (which exists) and Date (which doesn't). These are the types that you can expect the model to expose.

Upvotes: 2

Related Questions