aleczandru
aleczandru

Reputation: 5449

Displaying only date from DateTime

Hi I am trying to display only the date of the datetime property and the price of a decimal property formated in curency.But I must be doing something wrong because the formating does not work.This is how it is displayed:

enter image description here

I would like this to only display the date and the price using curency dolar amount. This is my models code:

    [Required]
    [DataType(DataType.Date)]
    public DateTime PublicationDate { get; set; }


    [Required]
    [DataType(DataType.Currency)]
    [DisplayFormat(DataFormatString="{0:c}")]
    public decimal Price { get; set; }

And this is the code that I used for the view:

         <p>
            @Html.LabelFor(model => model.PublicationDate , "Publication Date")
            @Html.TextBoxFor(model => model.PublicationDate, new { @class = "datepicker"})
         </p>
        <p>
            @Html.LabelFor(model => model.Price)
            @Html.TextBoxFor(model => model.Price)
         </p>

What am I doing wrong?

Upvotes: 2

Views: 6314

Answers (5)

aleczandru
aleczandru

Reputation: 5449

The problem was that the DataFormat anotations can not be applied to TextBoxFor and LabelFor they can only be applied to DisplayFor and EditorFor

Upvotes: 2

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

DateTime Formats for Date

[Required]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime PublicationDate { get; set; }

Double Formats for Currency

[Required]
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString="{0:0.00}")]
public decimal Price { get; set; }

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1499770

I'm not an MVC person, but I suspect you just want a DisplayFormatString:

[DisplayFormat(DataFormatString="{0:d}")]

d is a standard date/time format string for "short date". You could also use a custom date/time format string. Note that for text being displayed to a user, a standard date/time format is usually better as it can adjust for a user's culture appropriately. If you use a fixed custom format such as "MM/dd/yyyy" or "dd/MM/yyyy" then you'll end up confusing users who use different formats. (For example, "06/05/2013" is May 6th in the UK, but June 5th in the US.)

If you need this for input though, you'd probably be best off with a date picker.

Upvotes: 3

Freelancer
Freelancer

Reputation: 9064

You can simply assign it as>

DateTime.Now.Date.ToShortDateString()

Or in case of datetimepicker>

dateTimePicker1.Value.Date.ToShortDateString();

There is also option called Format in case of datetime picker keep it as short.

Upvotes: 0

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

You can use a formatting string "{0:d}" for the short date-only pattern.

Upvotes: 1

Related Questions