Changing date and time in MVC 3 C #

I am using MVC 3 with C #, and I am having trouble displaying dates in a drop down list. Dates are displayed as follows: 4/21/2011 12:00:00 AM, but I just want to format them as follows: 4/21/2011 , which is exactly the format in my database.

The date attribute in the database is the date, not the date and time.

Code in model:

[DisplayFormat(DataFormatString = "{mm/dd/yyyy}", ApplyFormatInEditMode=false)] public DateTime? booksDate { get; set; } 

the controller is as follows:

  var booksDates = from dates in db.Books orderby dates.booksDate select new { dates.booksDate}; ViewBag.Dates = BooksDates.Distinct(); 

and finally the code in my opinion:

 <td>Books dates</td> <td>@Html.DropDownList("booksDate", new SelectList(ViewBag.Dates as System.Collections.IEnumerable, "booksDate", "booksDate"), "Select a date") </td> 

Where am I mistaken?

thanks

+4
source share
6 answers

You can try using the regular html drop-down menu and manually set the html values. I am sure there is a better way, and it can be dirty, but it does its job.

Controller:

 ViewBag.Dates = BooksDates.Distinct(); 

View:

 <select> @foreach (var date in ViewBag.Dates) { <option> @Convert.ToDateTime(date.StartDate).ToShortDateString() </option> } </select> 
+5
source

If I'm not completely off, the DataFormatString should look like this:

 DataFormatString = "{0:MM/dd/yyyy}" 

or even simpler to use a short date format:

 DataFormatString="{0:d}" 
0
source

You can extend the helper class for completing tasks.

 public static class FormatHelper { public static IHtmlString ToDate( this HtmlHelper helper, DateTime datetime ) { return new HtmlString( datetime.ToShortDateString() ); } } 

In sight:

 @Html.ToDate( Model.Date ) 

Remember to import the namespace for viewing.

0
source

How and how in the controller:

 ViewBag.Date = Convert.ToDateTime(SelectedDate); 

in sight

 @Convert.ToDateTime(ViewData["Date"].ToString()).ToShortDateString() 

output:

02/03/2017

0
source

You can do this in pure C # by doing:

 string date = Convert.ToDateTime(date).ToShortDateString(); 
-1
source

if you use sql, you can do it like this:

 select field1, convert(nvarchar(10), field2, 101) 

from the table where // independently,

Let me explain what it is:

-field2 is the date containing the field. -nvarchar (10) is the type you will be updating. This does not really matter, because it is the type that you get (conversion result). Similarly, you do not need a data type. This is only for displaying data. The number 10 is the length of the string you get.

-field2:

field you want to convert (date with hour)

101: it's a style. This is reported by field2, which should only print month / day / year.

There are many styles, you must google them!

I hope this works.

-1
source

Source: https://habr.com/ru/post/1348168/


All Articles