How do I display the date, without the time in my View model? ASP.NET MVC4

bmanmike39
bmanmike39 used Ask the Experts™
on
I have a view model that i loop through with a foreach. I returns the data and time. i just want a short date.

foreach (var item in Model)
        {
            @item.Course
            @item.StartDate  // how would i show a short date here?

        }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
Call ToShortDateString:

@item.StartDate.ToShortDateString()

Open in new window


...or you can call ToString and pass a specific format:

@item.StartDate.ToString("MM/dd/yyyy")

Open in new window

Author

Commented:
I get an error on each of them

Error:
No overload for method 'ToString' takes 1 arguments
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
What is the data type of StartDate? If it's a nullable DateTime, then you'll have to call either of those methods against the Value property:

e.g.

@item.StartDate.Value.ToShortDateString()
@item.StartDate.Value.ToString("MM/dd/yyyy")

Open in new window


However, you'll want to check for null to avoid a NullReferenceException.

Author

Commented:
Thanks! That worked.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial