c# MVC5 #Html.EditorFor datepicker never displays the value - date

Sorry to bother but I've been headbanging on this topic for 8 hours
tried all the suggested solutions here and there and nothing changes (in good).
If someone could help... pleaaaase ...
I have a view supposed to display a datepicker without the hours
#Html.EditorFor(model => model.OrderDateFilter, new { #class = "form-control datepicker" , #value = "'" + Model.OrderDateFilter.ToString("dd/MM/yyyy") + "'"})
and the display is always THIS
error display
HTML result
<input class="text-box single-line" data-val="true" data-val-date="The field OrderDateFilter must be a date." data-val-required="Le champ OrderDateFilter est requis." id="OrderDateFilter" name="OrderDateFilter" type="date" value="09/02/2023">
So whatever the value it is never displayed except when I click the datepicker and choose a new date, I post the form to the controler, value is kept, processed and is correctly set back to 'value' but never shown
I've tried to TextBoxFor options with #type='date', etc...
Tryed use boostrap datepicker but it's obviously ugly and I could never get rid of the hour 00:00:00 format always displayed by default
Here's the Model part for this date filter (if I don't add the 2 first Annotations it's the same)
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime OrderDateFilter { get; set; } //---

18/03/2022 - EDIT
the date format in model etc.. MUST BE yyyy-MM-dd (because I don't need hours/minutes..) and no other format is possible. The datepicker displayed by Razor will pick the browser default culture to display the user's local format and will transate to yyyy-MM-dd in the controler etc..
then it works without jQuery datepicker or others

Related

How to convert/parse a string to a date object with Thymeleaf?

I am trying to parse string ISO dates (like "2016-01-01") to be able to format them.
#dates and #temporals seem to be only able to format Date/LocalDate/LocalDateTime objects.
For instance I want Thymeleaf to display "January 1st, 2016" when it is passed "2016-01-01".
Thanks.
Take a look the section Reformatting dates in our home page of the reference documentation.
....
...we can do just this:
WebContext ctx =
new WebContext(request, response, servletContext, request.getLocale()); ctx.setVariable("today",
Calendar.getInstance());
templateEngine.process("home", ctx, response.getWriter());
…and then perform date formatting in the view layer itself:
<p> Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span> </p>
I ended up implementing my own dialect containing utility functions such as parseISODate(String date) which returns a LocalDate then in the HTML I can do
th:text="${#temporals.format(#myDialect.parseISODate(someStringISODate), 'dd/MMM/yyyy')}"

How to edit date value with date type format in bootstrap

I have these codes but then the value display in the edit box is "mm/dd/yyyy"
#Html.TextBoxFor(m => m.StartDate, new { #Value = Model.StartDate.ToString("MM/dd/yyyy"), #placeholder= Model.StartDate.ToString("MM/dd/yyyy"), #class = "form-control", #type="date" })
How can I achieve something like this where the displayed date is the value from the database and not "mm/dd/yyyy"
First, don't set the value attribute directly. Razor will pretty much ignore this anyways. The value for a bound field comes from ModelState, which is itself composed of values from Request, ViewBag/ViewData, and Model, in that order. So, for example, if you want StartDate to default to "today", then you would simply populate your model with that in the action before you return the view:
model.StartDate = DateTime.Today;
Or, better, you can change the property on your model class to default to today automatically:
private DateTime? startDate;
public DateTime StartDate
{
get { return startDate ?? DateTime.Today; }
set { startDate = value; }
}
Just bear in mind that if your action happens to take a param like startDate or you set something like ViewBag.StartDate, those values will always take precedence.
Second, you're utilizing an HTML5 date input type. In browsers that support the HTML5 input types, the supplied value for a datetime, date or time, must be in ISO format. For a date, that means YYYY-MM-DD. If the value is not supplied like that, then the browser considers it garbage and discards it, leaving the control as if no value was supplied.
Also, FWIW, you don't need to prefix every member of your anonymous object with #. It doesn't technically hurt anything, but it's code smell. The # prefix exists to escape language keywords. With class, for example, you can't use it directly since it's a keyword, so you have to use #class instead. However, things like placeholder and type are not keywords, and therefore don't need an # prefix.

Laravel 5.1 Won't save date into database set as 00-00-00 00:00:00

I'm sending dates up using this Bootstrap datetimepicker with a format of MMM D, YYY created by MomentJS, which can't submit a different format than what is displayed to the user by default.
So on the server-side I added an mutator for the date in the model:
public function setStartDateAttribute($startDate) {
//dd(Carbon::parse($startDate)->toDateTimeString());
return Carbon::parse($startDate)->toDateTimeString();
}
Which when I dd the value looks like it should 2015-10-22 00:00:00, but it saves the date as 0000-00-00 00:00:00 or it just isn't setting the date at all, which I don't understand.
I don't want to change how the timestamps are formatted in the database so I didn't set $dateFormat and set 'start_date' in the $dates array of the Model. Thought an mutator seemed easier. The field is set to date() in the migration file, and I'm pretty sure I've done this before and it just worked. So I tried it in the my controller without the mutator and the same line works:
public function update(TournamentRequest $request, $tournamentId)
{
// Update a tournament with all fillable data, and persist to database
$tournament = Tournament::find($tournamentId)->fill($request->except('start_date'));
$tournament->start_date = Carbon::parse($request->start_date)->toDateTimeString();
$tournament->save();
return Redirect::route('dashboard.tournaments.index');
}
Why does the same code work inside the controller without the mutator setup in the Model, but not work when using the mutator?
This is how you make a setter method for your attribute. Note: you don't return anything, you just assign a value to the attribute:
public function setStartDateAttribute($startDate) {
$this->attributes['start_date'] = Carbon::parse($startDate)->toDateTimeString();
}
That's assuming you want to set a field named start_date in your table.

grails change Date format in gsp view

When I try to use date format tag in gsp view to change the format of my date but it doesn't work.
This is my code:
class MyDate {
Date date
}
MyDateController:
....
def unixSeconds = params["date"].replaceAll("\"", "") as long //params["date"]="1386157660"
Date date = new Date(unixSeconds*1000L)
myDateInstance = new MyDate(date:date)
....
gsp View:
${myDateInstance.date.format('yyyy-MM-dd HH:mm')}
The format that I have is 2013-12-04 12:47:40.0 instead of 2013-12-04 12:47
Afaict, that shouldn't happen and I can't see how it is happening...
Are you sure that's the line of code that's generating the output you're seeing?
You could try the Grails formatDate tag in its place:
<g:formatDate format="yyyy-MM-dd HH:mm" date="${myDateInstance.date}"/>
You can use "formatDate" in value attribute like following
<g:textField name="saleDate" value="${formatDate(format:'dd-MM-yyyy',date:saleItem?.saleDate)}"/>
In addition to #tim_yates's answer above, there is another point I want to add:
I observed that if type and style are given, format is not used. I think they work as alternatives for each other. Also, using format would be beneficial as the Date string format could differ on different operating systems.

How to pass Date values as params in Grails

I have seen a few posts related to using the g:datePicker in Grails. Using this it looks like you can just pick the value off the params like so params.myDate.
However, when I try to do something like this in my view:
view:
<g:link controller="c" action="a" params="[fromDate:(new Date())]">
controller:
def dateval = params.fromDate as Date
The date is not parsing out correctly. Is there something else I should be doing in the view to make the date 'parsable' by the controller. I've looked around and haven't found this in any posts where datePicker is not used.
I prefer to send time instead of dates from the client.
<g:link controller="c" action="a" params="[fromDate:(new Date().time)]">
And in action I use the constructor of Date that takes time.
def date = params.date
date = date instanceof Date ? date : new Date(date as Long)
I have created a method in DateUtil class to handle this. This works fine for me.
When the parameters are sent to a controller they are sent as strings. The following won't work
def dateval = params.fromDate as Date
Because you haven't specified what date format to use to convert the string to a date. Replace the above with:
def dateval = Date.parse('yyyy/MM/dd', params.fromDate)
Obviously if your date is not sent in the format yyyy/MM/dd you'll need to change the second parameter. Alternatively, you can make this conversion happen automatically by registering a custom date editor
Whatever is sent from view is a string so params.fromDate as Date does not work.
In grails 2.x a date method is added to the params object to allow easy, null-safe parsing of dates, like
def dateval = params.date('fromDate', 'dd-MM-yyyy')
or you can pass a list of date formats as well, like
def dateval = params.date('fromDate', ['yyyy-MM-dd', 'yyyyMMdd', 'yyMMdd'])
or the format can be read from the messages.properties via key date.myDate.format and use date method of params as
def dateval = params.date('fromDate')