How to extract only month, day and year portion of datetime from DateTime string?

1.9k views Asked by At

I'm writing DateTime Formatter in ASP.NET MVC and need to format the datetime based on cultural info.

My model's property binds DateTime.Now volue to the view and as a result the view is displaying 3/21/2017 9:38:37 AM as a datetime.

I'm looking for the way to display 3/21/2017 or 21/3/2017 and etc based on the culture.

What is the best way to do it. I tried a few examples from

https://msdn.microsoft.com/en-us/library/5hh873ya(v=vs.90).aspx

<span>String.Format("{0:d}", @Model.ToString())</span>

But the view still display the full datetime value: 3/21/2017 9:38:37 AM

I know that might be easy question but anywhere need some input on that.

What is the best way to handle something like that?

1

There are 1 answers

0
Cameron Hurst On

C# has come helpers built into the DateTime class. You can do this to only get the date.

DateTime.Now.ToShortDateString();

Or using your code assuming mode is an instance of DateTime:

@Model.ToShortDateString()