FIVE MANGO
FIVE MANGO

Reputation: 31

How to convert DateTime to Date in ASP.NET Core (working with database)

I'm working with asp.net core in visual studio 2017

I will need to use C#, MVC, or SQL to solve this

I'm creating a table with a foreach statement (below)

        <table>
           <tbody>
                @foreach (var item in Model)
                {
                <tr>

                    <td>
                        @Html.DisplayFor(modelItem => item.Month)
                    </td>

                    <td>
                        @Html.DisplayFor(modelItem => item.Temperature)
                    </td>

                    <td>
                        @Html.DisplayFor(modelItem => item.StartDate)
                    </td>

                    <td>
                        @Html.DisplayFor(modelItem => item.EndDate)
                    </td>

                </tr>
                }
            </tbody>
        </table>

and I'm trying to modify this model data to display only the Date.

        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }

How would I do this so that all of my model items are effected?

Here are my controller actions

 public IActionResult Create()
        {
            return View();
        }

and

        [HttpPost]
        public async Task<IActionResult> Create(Data data)
        {
            if (ModelState.IsValid)
            {
                _context.Add(data);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(data);
        }

Upvotes: 0

Views: 6014

Answers (2)

Peter B
Peter B

Reputation: 24270

You can annotate your model with DisplayFormat attributes:

using System.ComponentModel.DataAnnotations;

public class DateModel
{
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime StartDate { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime EndDate { get; set; }
}

Or if you want to avoid repeating these, you can also use a constant:

using System.ComponentModel.DataAnnotations;

public class DateModel
{
    [DisplayFormat(DataFormatString = Constants.DateOnlyFormat)]
    public DateTime StartDate { get; set; }

    [DisplayFormat(DataFormatString = Constants.DateOnlyFormat)]
    public DateTime EndDate { get; set; }
}

public static class Constants
{
    public const string DateOnlyFormat = "{0:MM/dd/yyyy}";
}

Upvotes: 1

Praveen Rai
Praveen Rai

Reputation: 845

Use the Date property of DateTime structure.

<td>
      @Html.DisplayFor(modelItem => item.StartDate.Date.ToString("d"))
</td>

For more details refer :

Upvotes: 0

Related Questions