Display only date and no time

238,114

Solution 1

If the column type is DateTime in SQL then it will store a time where you pass one or not.

It'd be better to save the date properly:

model.ReturnDate = DateTime.Now;

and then format it when you need to display it:

@Html.Label(Model.ReturnDate.ToShortDateString())

Or if you're using EditorFor:

@Html.EditorFor(model => model.ReturnDate.ToShortDateString())

or

@Html.EditorFor(model => model.ReturnDate.ToString("MM/dd/yyyy"))

To add a property to your model add this code:

public string ReturnDateForDisplay
{
    get
    {
       return this.ReturnDate.ToString("d");
    }
}

Then in your PartialView:

@Html.EditorFor(model => model.ReturnDateForDisplay)

EDIT:

I just want to clarify for this answer that by my saying 'If you're using EditorFor', that means you need to have an EditorFor template for the type of value you're trying to represent.

Editor templates are a cool way of managing repetitive controls in MVC:

http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

You can use them for naive types like String as I've done above; but they're especially great for letting you template a set of input fields for a more complicated data type.

Solution 2

Just had to deal with this scenario myself - found a really easy way to do this, simply annotate your property in the model like this:

[DataType(DataType.Date)]
public DateTime? SomeDateProperty { get; set; }

It will hide the time button from the date picker too.

Sorry if this answer is a little late ;)

Solution 3

This works if you want to display in a TextBox:

@Html.TextBoxFor(m => m.Employee.DOB, "{0:dd-MM-yyyy}")

Solution 4

The date/time in the datebase won't be a formatted version at all. It'll just be the date/time itself. How you display that date/time when you extract the value from the database is a different matter. I strongly suspect you really just want:

model.Returndate = DateTime.Now.Date;

or possibly

model.Returndate = DateTime.UtcNow.Date;

Yes, if you look at the database using SQL Server Studio or whatever, you'll now see midnight - but that's irrelevant, and when you fetch the date out of the database and display it to a user, then you can apply the relevant format.

EDIT: In regard to your edited question, the problem isn't with the model - it's how you specify the view. You should use something like:

@Html.EditorFor(model => model.Returndate.Date.ToString("d"))

where d is the standard date and time format specifier for the short date pattern (which means it'll take the current cultural settings into account).

That's the bit I've been saying repeatedly - that when you display the date/time to the user, that's the time to format it as a date without a time.

EDIT: If this doesn't work, there should be a way of decorating the model or view with a format string - or something like that. I'm not really an MVC person, but it feels like there ought to be a good way of doing this declaratively...

Solution 5

You can modify your ViewModel as below:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]
Share:
238,114
ZVenue
Author by

ZVenue

Your persistence is a measure of faith you have in your abilities.

Updated on December 25, 2020

Comments

  • ZVenue
    ZVenue over 3 years

    In MVC razor, I am putting current date in the database like this..

    model.Returndate = DateTime.Now.Date.ToShortDateString();
    

    Since the database field is a datetime datatype and I am converting the current date to string format, this is not working.. how can I do this? I am doing the string format because I want the date in mm/dd/yyyy format and not in mm/dd/yyyy hh:mm:ss time format..

    EDIT:

    In the controller I have

    var model = new ViewModel();
    model.ReturnDate = DateTime.Now;            
    return PartialView("PartialView", model);  
    

    In the partialview, I have

    @Html.EditorFor(model => model.Returndate)
    

    This is where its displaying the date as Date and Time together... I want just the date to be displayed. Not the time. I hope this edit explains better.

  • Russ Clarke
    Russ Clarke over 12 years
    that won't help the issue of saving the date though.
  • Jalal Said
    Jalal Said over 12 years
    Can't he save it with calling model.Returndate.ToString("mm/dd/yyyy")?
  • ZVenue
    ZVenue over 12 years
    Thats a problem.. I am putting that value in a datetime field in the db. So this will not work..please see my original post.
  • Bodrick
    Bodrick over 12 years
    Shouldn't it be .ToString("MM/dd/yyyy")? mm is minutes, not months!
  • Jalal Said
    Jalal Said over 12 years
    @Bodrich: thanks, updated, I just copy paste his pattern though.
  • ZVenue
    ZVenue over 12 years
    not sure who downvoted this.. but I am not using the HTML.label to display this.. I am using HTML.EditorFor(model => model.Returndate) how do I format the display in this case...
  • ZVenue
    ZVenue over 12 years
    The DateTime.Now.Date still displays the time along with the date.
  • Jalal Said
    Jalal Said over 12 years
    @ZVenue: you can load it the same way DateTime.Parse or DateTime.ParseExact and apply the pattern, but I think @Jon answer is better apply here.
  • Russ Clarke
    Russ Clarke over 12 years
    That was just an example of how to format your result; I'll update my answer.
  • Jon Skeet
    Jon Skeet over 12 years
    @ZVenue: Displays it where? You should be storing a DateTime value, and using a date-only format specifier wherever you're displaying the date. The code you've given (setting a property in the model) is presumably for storage, so it doesn't matter that it's got a time of midnight.
  • Russ Clarke
    Russ Clarke over 12 years
    Jon's suggesting what I was talking about, saving the date to SQL as it stands; you can then just format your date appropriately when you print it.
  • Jon Skeet
    Jon Skeet over 12 years
    I think if the value is logically only a date, it's worth storing just the date part as well, even if the time is going to be stripped on display anyway.
  • Daniel A. White
    Daniel A. White over 12 years
    The Label parameter isn't the date time.
  • Russ Clarke
    Russ Clarke over 12 years
    Indeed, but ZVenue didn't actually say how he was displaying it at the point I wrote that snippet, I was simply trying to illustrate how you should save the data intact, and then format it to the way you require when you display it.
  • ZVenue
    ZVenue over 12 years
    Sorry I didnt say what I was doing with that date time .. I am displaying it in a partial view like @Html.EditorFor(model => model.Returndate)..thasts where this is displayed as date and time together... I want just the date to be displayed in this html.editorfor
  • ZVenue
    ZVenue over 12 years
    @Russ: the editorfor update you made did not work. Its giving me an error "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."
  • ZVenue
    ZVenue over 12 years
    Please see my Edit to the original post. This should explain better.
  • ZVenue
    ZVenue over 12 years
    Please see my Edit to the original post. This should explain better.
  • ZVenue
    ZVenue over 12 years
    Please see my Edit to the original post. This should explain better.
  • Jalal Said
    Jalal Said over 12 years
    @ZVenue you should put the string format there then, check my answer edit.
  • Jon Skeet
    Jon Skeet over 12 years
    @ZVenue: Edited the answer... basically it was exactly what I've been saying before: you need to change how you display the value, not how you store it.
  • Jon Skeet
    Jon Skeet over 12 years
    @Russ: It happens sometimes :(
  • Russ Clarke
    Russ Clarke over 12 years
    John skeets answer has everything you need, if you do get that template error again, consider making in a get property on your model that returns the formatted date.
  • ZVenue
    ZVenue over 12 years
    @Jon:I am getting this error when I used your edit code for html.editorfor...."Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions"....at run time
  • ZVenue
    ZVenue over 12 years
    @Jalal: Again I am getting the same error..."Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."
  • ZVenue
    ZVenue over 12 years
    @RussC: Yes I am getting that template error.. and I am not sure what you mean by "get property on your model that returns the formatted date".. Appreciate your help.
  • Jon Skeet
    Jon Skeet over 12 years
    @ZVenue: Then you need to look on ASP.NET MVC tutorials for how to apply formatting to values - which isn't really specific to DateTime. I'll have a look too...
  • Jon Skeet
    Jon Skeet over 12 years
    @ZVenue: It could well be that DisplayFormatAttribute is what you're after: msdn.microsoft.com/en-us/library/…
  • Jon Skeet
    Jon Skeet over 12 years
    @ZVenue: Have a look at this too: stackoverflow.com/questions/5033902/…
  • James Reategui
    James Reategui about 12 years
    you should remove '@Html.EditorFor(model => model.ReturnDate.ToShortDateString())' from the answer because that does not work.
  • Russ Clarke
    Russ Clarke about 12 years
    Actually it works fine but you have to have implemented an Editor template for the type of value. Here's a handy guide: coding-in.net/asp-net-mvc-3-how-to-use-editortemplates
  • Dmytro
    Dmytro over 11 years
    Thanks a lot. It was very helpful post for me! +1
  • RealityDysfunction
    RealityDysfunction almost 11 years
    Just what I needed. Excellent!
  • John
    John over 10 years
    "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" above html.editorfor won't work
  • John
    John over 10 years
    I had a sitation recently where chrome put funny stuff in when input type is date, part of html5 i think, I wanted to use jquery datepicker instead so I went with DataType.Text - that still allowed me to use formatting cool enough
  • Jon Skeet
    Jon Skeet over 10 years
    @John: Hmm - not sure then, to be honest. But hopefully the answer at least gives the flavour of what's wrong, even if the MVC-specific bits aren't quite right.
  • mkataja
    mkataja over 10 years
    Editor templates are cool but unnecessarily complicated here when you can just use a DataType annotation.
  • Russ Clarke
    Russ Clarke over 10 years
    @mkataja Yes; but check the dates; this was MVC3; Also, and more relevant; You can use a data type annotation, but data format is a different beast; we always knew it was a day time, he just wanted to render it differently.
  • RyanfaeScotland
    RyanfaeScotland almost 9 years
    No need to apologise for being late, posting answers to old questions can be a great help for people who aren't OP. This is the answer I was looking for as I knew it was possible but couldn't remember how, and you posted it 3 years ago. If anything you are incredibly early.
  • Ciaran Gallagher
    Ciaran Gallagher almost 9 years
    Yep this would also work in Razor syntax, e.g. @Html.Encode(string.Format("0:D", item.Modify_Date))
  • Oleg Sh
    Oleg Sh over 8 years
    date will be shown incorrectly if browser has different format in settings than "dd-MM-yyyy", i.e "MM-dd-yyyy"
  • Zenacity
    Zenacity over 7 years
    I was getting the error "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions." as described above. Converting it to a string and then displaying it in the view worked for me... @{String DateEdited = (string)Convert.ChangeType(item.DateLastEdited.ToShortDateSt‌​ring(), typeof(string));} @DateEdited
  • Antoine Pelletier
    Antoine Pelletier over 7 years
    if the date comes from a database i don't know how this could help... can't figure it out
  • Nathan McKaskle
    Nathan McKaskle almost 7 years
    This isn't working, it says there is no method called ToString or even ToShortDateString() when trying to use it with DisplayFor(modelItem = item.migrationdate.ToShortDateString())
  • Shady
    Shady almost 7 years
    FYI, it doesn't work with me without date format [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] stackoverflow.com/questions/14212527/…
  • Katherine
    Katherine almost 6 years
    This solution also solves the problem of Chrome's datepicker conflict. If you just specify Datatype.Date in Viewmodel, Chrome uses its own version of datepicker in textbox. Thank you!
  • L. Guthardt
    L. Guthardt almost 6 years
    Please have a look at the other answers. Do you think yours is necessary and adds some new quality content to the post?
  • Christoph B
    Christoph B over 2 years
    How does specifying the format deal with localization?
  • Abdul Hannan
    Abdul Hannan over 2 years
    Will this have an Impact on SQL If we are using EF Code first Approach ?
  • cvillalobosm
    cvillalobosm over 2 years
    Thanks @ANJYR, this one did the trick for me. I am using PickADay library for DateTime fields. Maybe that is why any of the other proposed solutions worked in my case.