I am building some form (ASP.NET MVC). I have there a datetime input field. I am passing viewmodel to the view with initialized value of property with date (DateTimeOffset.Now). The problem is that date-time picker that is generated in a browser have also seconds and miliseconds that I don't need.
I saw asnwers for similiar questions, and people were advising to add format, but when I add format, then input field is not generated with default value (the one passed with viewmodel), visible value is: "dd.mm.rrrr --:--" (probably default date formatting for my country). When I look into html, I see that in value property there is proper value ("17.01.2022 12:22").
When I select value from default datetime picker, than everything is ok, even when I submit form (httpost) and values are reloaded.
<form asp-action="ScheduleItemsAdd" method="post">
<div >
<label asp-for="FirstVisitDateTime" ></label>
<input asp-for="FirstVisitDateTime" asp-format="{0:dd.MM.yyyy hh:mm}">
<button type="submit" >Add</button>
</div>
When I remove "asp-format="{0:dd.MM.yyyy hh:mm}" it will load initial value, but will show seconds and milisecond in date time picker.
private DateTimeOffset? _firstVisitDateTime;
[DataType(DataType.DateTime)]
[DisplayFormat( ApplyFormatInEditMode = true)]
public DateTimeOffset FirstVisitDateTime
{
get
{
if (_firstVisitDateTime.HasValue)
{
return _firstVisitDateTime.Value;
}
else
{
return DateTimeOffset.Now;
}
}
set { _firstVisitDateTime = value; }
}
I want to load initial value (or just DateTime.Now) and use default date-time picker without seconds and milisseconds.
Any advice?
CodePudding user response:
Switch:
[DataType(DataType.Datetime)]
to:
[DataType(DataType.Date)]
This will only display the date portion in the browser.
CodePudding user response:
If it is okay , you can change your input field display type as string instead and then at backed you can use C# code to format date time i.e.
mydatetime.ToString("{0:dd.MM.yyyy hh:mm}");
and at frontend you can use moment.JS to change the input field's format