Reputation: 11
I have encountered a small problem while making a project in ASP.NET Core MVC.
I'm making a car service, where you can make some reservations. Here's the code for my Customers.cs in Models folder:
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
public DateTime CustomerCarDateDayTime { get; set; }
On the page in Create site I can add new reservation and here is ok I think - the problem occurs when I want to see all the reservations that have been made in Index:
As you can see, the date is not properly displayed on Index site. Under the column of the date there is 01.01.0001 00:00 and not the actual date that was chosen for the reservation.
As far, I have tried modifying the Customers.cs to the point that is above. I have also tried modifying the Index.cshtml in Views
<td>
@Html.DisplayFor(modelItem => item.CustomerCarDateDayTime)
</td>
because I thought that maybe the problem with displaying date may be in View section, but it didn't helped - as the result of some of my actions, the field became even empty, so I have stopped modifying here.
I was looking for some solutions in Google, some of them I have tried (the results didn't helped much), so in the end I'm still stuck with this. I'm a self learner, I'm using Visual Studio 2022 for this project.
Due to suggestion, here's my code in CustomersController.cs
// GET: Customers
public async Task<IActionResult> Index()
{
return View(await _context.Customers.ToListAsync());
}
Upvotes: 1
Views: 188
Reputation: 41
I have encountered the same issue in the past. It is because all the dates in ASP.NET Core are stored in ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ). You need to make sure that when you send dates from the frontend the format should match so in order to store dates you need to send the exact format from the frontend so that the backend can understand. You can change in the ApplicationDbContenxt to enforce UTC storage (or any type of date you want)
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Event>()
.Property(e => e.StartDate)
.HasColumnType("datetime2")
.HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
builder.Entity<Event>()
.Property(e => e.EndDate)
.HasColumnType("datetime2")
.HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
}
You can convert the date in any format you want in the frontend when receiving the response from the backend.
Upvotes: 0