Grails input error: property must be a valid date - grails

I have a text input that uses custom date and time picker script.
<div class="input-group date datetime" data-start-view="4" data-date-format="dd MM yyyy" data-min-view="2" data-link-field="dtp_input1">
<input name="dateOfBirth" class="form-control" size="16" type="text" value="${userInstance?.dateOfBirth}"/>
<span class="input-group-addon btn btn-primary"><span class="glyphicon glyphicon-th"></span></span>
</div>
It gives me this error
Property org.springframework.context.support.DefaultMessageSourceResolvable: codes [rms.User.dateOfBirth,dateOfBirth]; arguments []; default message [dateOfBirth] must be a valid Date
I dont how to solve this. Using the grails dateTime picker tag seems to work but its ugly

The only way is to use SimpleDateFormat. I often use it for forms with a JS-calendar inside:
class YourController {
static SimpleDateFormat sdf = new SimpleDateFormat( 'dd.MM.yyyy' )
def index(){
Date dateOfBirth
try{
if( params.dateOfBirth ) dateOfBirth = sdf.parse( params.dateOfBirth )
}catch( Exception ignoreMe ){}
// do something useful
}
UPDATE:
You must use the propper date format of course. The one I gave in my example dd.MM.yyyy corresponds to 08.02.2014. For strings like February 08 2014 you are gonna need something like MMM dd yyyy.
See http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html for further info

Related

Displaying a DateTime in MVC [duplicate]

I have a .Net MVC 5 application that is using Data Annotations, Entity-Framework Jquery 2.1.3 and Jquery UI 1.11.4.
When I render an edit form with an input of type date using the UK format "dd/MM/YYYY"; the following error message appears when using Google Chrome:
The specified value '10/10/2001' does not conform to the required format, 'yyyy-MM-dd'. jquery-2.1.3.js:5317
Model
public class MyModel
{
[Column(TypeName = "date"), DataType(DataType.Date), Display(Name = "My date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public string MyDate { get; set; }
}
Mark up
<input class="text-box single-line" data-val="true" data-val-date="The field My date must be a date." id="MyDate" name="MyDate" type="date" value="10/10/2001" />
The value is set correctly in the input control but the date does not appear in the browser. I first thought this was an issue with jQuery as it is appearing the jQuery script file, but when testing in IE and Firefox everything is working fine.
I then assumed it was my regional setting in chrome as by default Chrome thinks everyone English is in America, I changed the regional setting to UK and still the same issue appears.
A simple fix would be to change the format in my model to universal but to UK users this is a little alien.
Is there a way to tell chrome that accept date formats in "dd/MM/YYYY"?
The specifications for the HTML5 date picker state that the date must be in the format yyyy-MM-dd (ISO format). This means that you DisplayFormatAttribute must be
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public string MyDate { get; set; }
Alternatively you can manually add the format using
#Html.TextBoxFor(m => m.MyDate, "{0:yyyy-MM-dd}", new { #type = "date" })
The later option allows you to keep the DataFormatString = "{0:dd/MM/yyyy}") for usage in #Html.DisplayFor()
You don't need any jquery or ASP feature for fixing it. Simple JS will do just fine.
The problem is that the browser requires the format yyyy-mm-dd.
And toLocaleString doesn't allow the date to be in this format. So after searching I found out that this is ISO format and we can use Date().toISOString() to get the date in the required format.
I used the slice method to extract the date part only because Date().toISOString() returns date with time.
My code:
date: new Date().toISOString().slice(0, 10)
The issue could be from the type="date". That was my situation anyway. Worked once it was changed to type="text". If the interface is built with an MVC wrapper, you need to replace or set the html attribute accordingly.
You can use the InputTagHelper.Format
<input asp-for="MyDate" asp-format="{0:yyyy-MM-dd}" />
https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Mvc/TagHelpers/InputTagHelper/#prop-Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Format
I was facing the same problem
I Did this and it started working
<input type="date" class="form-control text-box single-line" id="EndDate" name="EndDate" value=#Model.EndDate.ToString("yyyy-MM-dd") />
Set the type attribute to text.
#Html.TextBoxFor(m => m.MyDate, new { #type = "text" })
I'd like to highlight something in the answer here.
If you are building an application that has Globalization and Localization then the method of passing in a format using a Html helper will be better. You can also just use EditorFor and pass in the necessary id or class for datepicker.
I was getting this warning by assigning the value to html5 date input. I just converted to the required format(yyyy-MM-dd) according then its fine.
All my logic is to calculate next date and assign to other date input. I'll share my whole logic.
HTML Code:
<input type='date' name="booking_starts" id="booking_starts" autocomplete="off" />
<input type='date' name="booking_ends" id="booking_ends" autocomplete="off" />
Js Code:
$('#booking_starts').change(function() {
var start = $("#booking_starts").val();
var result = new Date(start);
var end = result.setDate(result.getDate() + 1);
$("#booking_ends").val(dateToYMD(end));
});
function dateToYMD(end_date) {
var ed = new Date(end_date);
var d = ed.getDate();
var m = ed.getMonth() + 1;
var y = ed.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
If anyone else comes across this, in my case it was because the day in my date had only one digit and this was messing it up. If your date day is less than 10, make sure to do new Date().toLocaleString("en-US", { day: "2-digit" });

DateTime Format not recognized in input for Date [duplicate]

I have a .Net MVC 5 application that is using Data Annotations, Entity-Framework Jquery 2.1.3 and Jquery UI 1.11.4.
When I render an edit form with an input of type date using the UK format "dd/MM/YYYY"; the following error message appears when using Google Chrome:
The specified value '10/10/2001' does not conform to the required format, 'yyyy-MM-dd'. jquery-2.1.3.js:5317
Model
public class MyModel
{
[Column(TypeName = "date"), DataType(DataType.Date), Display(Name = "My date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public string MyDate { get; set; }
}
Mark up
<input class="text-box single-line" data-val="true" data-val-date="The field My date must be a date." id="MyDate" name="MyDate" type="date" value="10/10/2001" />
The value is set correctly in the input control but the date does not appear in the browser. I first thought this was an issue with jQuery as it is appearing the jQuery script file, but when testing in IE and Firefox everything is working fine.
I then assumed it was my regional setting in chrome as by default Chrome thinks everyone English is in America, I changed the regional setting to UK and still the same issue appears.
A simple fix would be to change the format in my model to universal but to UK users this is a little alien.
Is there a way to tell chrome that accept date formats in "dd/MM/YYYY"?
The specifications for the HTML5 date picker state that the date must be in the format yyyy-MM-dd (ISO format). This means that you DisplayFormatAttribute must be
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public string MyDate { get; set; }
Alternatively you can manually add the format using
#Html.TextBoxFor(m => m.MyDate, "{0:yyyy-MM-dd}", new { #type = "date" })
The later option allows you to keep the DataFormatString = "{0:dd/MM/yyyy}") for usage in #Html.DisplayFor()
You don't need any jquery or ASP feature for fixing it. Simple JS will do just fine.
The problem is that the browser requires the format yyyy-mm-dd.
And toLocaleString doesn't allow the date to be in this format. So after searching I found out that this is ISO format and we can use Date().toISOString() to get the date in the required format.
I used the slice method to extract the date part only because Date().toISOString() returns date with time.
My code:
date: new Date().toISOString().slice(0, 10)
The issue could be from the type="date". That was my situation anyway. Worked once it was changed to type="text". If the interface is built with an MVC wrapper, you need to replace or set the html attribute accordingly.
You can use the InputTagHelper.Format
<input asp-for="MyDate" asp-format="{0:yyyy-MM-dd}" />
https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Mvc/TagHelpers/InputTagHelper/#prop-Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Format
I was facing the same problem
I Did this and it started working
<input type="date" class="form-control text-box single-line" id="EndDate" name="EndDate" value=#Model.EndDate.ToString("yyyy-MM-dd") />
Set the type attribute to text.
#Html.TextBoxFor(m => m.MyDate, new { #type = "text" })
I'd like to highlight something in the answer here.
If you are building an application that has Globalization and Localization then the method of passing in a format using a Html helper will be better. You can also just use EditorFor and pass in the necessary id or class for datepicker.
I was getting this warning by assigning the value to html5 date input. I just converted to the required format(yyyy-MM-dd) according then its fine.
All my logic is to calculate next date and assign to other date input. I'll share my whole logic.
HTML Code:
<input type='date' name="booking_starts" id="booking_starts" autocomplete="off" />
<input type='date' name="booking_ends" id="booking_ends" autocomplete="off" />
Js Code:
$('#booking_starts').change(function() {
var start = $("#booking_starts").val();
var result = new Date(start);
var end = result.setDate(result.getDate() + 1);
$("#booking_ends").val(dateToYMD(end));
});
function dateToYMD(end_date) {
var ed = new Date(end_date);
var d = ed.getDate();
var m = ed.getMonth() + 1;
var y = ed.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
If anyone else comes across this, in my case it was because the day in my date had only one digit and this was messing it up. If your date day is less than 10, make sure to do new Date().toLocaleString("en-US", { day: "2-digit" });

Specific date format string not being displayed in Edit mode [duplicate]

I have a .Net MVC 5 application that is using Data Annotations, Entity-Framework Jquery 2.1.3 and Jquery UI 1.11.4.
When I render an edit form with an input of type date using the UK format "dd/MM/YYYY"; the following error message appears when using Google Chrome:
The specified value '10/10/2001' does not conform to the required format, 'yyyy-MM-dd'. jquery-2.1.3.js:5317
Model
public class MyModel
{
[Column(TypeName = "date"), DataType(DataType.Date), Display(Name = "My date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public string MyDate { get; set; }
}
Mark up
<input class="text-box single-line" data-val="true" data-val-date="The field My date must be a date." id="MyDate" name="MyDate" type="date" value="10/10/2001" />
The value is set correctly in the input control but the date does not appear in the browser. I first thought this was an issue with jQuery as it is appearing the jQuery script file, but when testing in IE and Firefox everything is working fine.
I then assumed it was my regional setting in chrome as by default Chrome thinks everyone English is in America, I changed the regional setting to UK and still the same issue appears.
A simple fix would be to change the format in my model to universal but to UK users this is a little alien.
Is there a way to tell chrome that accept date formats in "dd/MM/YYYY"?
The specifications for the HTML5 date picker state that the date must be in the format yyyy-MM-dd (ISO format). This means that you DisplayFormatAttribute must be
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public string MyDate { get; set; }
Alternatively you can manually add the format using
#Html.TextBoxFor(m => m.MyDate, "{0:yyyy-MM-dd}", new { #type = "date" })
The later option allows you to keep the DataFormatString = "{0:dd/MM/yyyy}") for usage in #Html.DisplayFor()
You don't need any jquery or ASP feature for fixing it. Simple JS will do just fine.
The problem is that the browser requires the format yyyy-mm-dd.
And toLocaleString doesn't allow the date to be in this format. So after searching I found out that this is ISO format and we can use Date().toISOString() to get the date in the required format.
I used the slice method to extract the date part only because Date().toISOString() returns date with time.
My code:
date: new Date().toISOString().slice(0, 10)
The issue could be from the type="date". That was my situation anyway. Worked once it was changed to type="text". If the interface is built with an MVC wrapper, you need to replace or set the html attribute accordingly.
You can use the InputTagHelper.Format
<input asp-for="MyDate" asp-format="{0:yyyy-MM-dd}" />
https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Mvc/TagHelpers/InputTagHelper/#prop-Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Format
I was facing the same problem
I Did this and it started working
<input type="date" class="form-control text-box single-line" id="EndDate" name="EndDate" value=#Model.EndDate.ToString("yyyy-MM-dd") />
Set the type attribute to text.
#Html.TextBoxFor(m => m.MyDate, new { #type = "text" })
I'd like to highlight something in the answer here.
If you are building an application that has Globalization and Localization then the method of passing in a format using a Html helper will be better. You can also just use EditorFor and pass in the necessary id or class for datepicker.
I was getting this warning by assigning the value to html5 date input. I just converted to the required format(yyyy-MM-dd) according then its fine.
All my logic is to calculate next date and assign to other date input. I'll share my whole logic.
HTML Code:
<input type='date' name="booking_starts" id="booking_starts" autocomplete="off" />
<input type='date' name="booking_ends" id="booking_ends" autocomplete="off" />
Js Code:
$('#booking_starts').change(function() {
var start = $("#booking_starts").val();
var result = new Date(start);
var end = result.setDate(result.getDate() + 1);
$("#booking_ends").val(dateToYMD(end));
});
function dateToYMD(end_date) {
var ed = new Date(end_date);
var d = ed.getDate();
var m = ed.getMonth() + 1;
var y = ed.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
If anyone else comes across this, in my case it was because the day in my date had only one digit and this was messing it up. If your date day is less than 10, make sure to do new Date().toLocaleString("en-US", { day: "2-digit" });

Mobiscroll Default Date Value on Safari

I'm using mobiscroll date scroller in an app. I have it set up to initialize to a date I get from the database and set as the value of my input field. Here is my code:
$(function(){
$("#requestDate").scroller({
preset: 'date',
theme: 'jqm',
display: 'modal',
mode: 'scroller',
dateOrder: 'mdyyyy',
dateFormat: 'm/d/yyyy'
});
var requestDate = $("#requestDate").val();
if(requestDate != ""){
requestDate = new Date(requestDate);
$("#requestDate").scroller('setDate', requestDate, true);
}
});
Here is my form field:
<input type="text" name="requestDate" id="requestDate" data-role="mobiscroll" value="2013,7,25" data-mini="true" readonly="" class="ui-input-text ui-body-f ui-corner-all ui-shadow-inset ui-mini">
This shows the date formatted in the text input and defaults to that date when mobiscroll is opened. Except for in Safari. In safari the date shows as NaN/NaN/NaN. How do I fix this?
Thanks!
You don't need to call setDate, just put the date in the correct format as the input value.
See example: http://jsfiddle.net/RQzbw/
Note 1: Use 'mdyy' and 'm/d/yy', yyyy is incorrect (see documentation)
Note 2: .scroller() is deprecated, use .mobiscroll() instead. If you are using an older version, you should upgrade to latest.

How to make jqueryUI datepicker submit in a different format than what is being displayed?

I'm working on some internationalization using jQueryUI. I have a DatePicker control on a form that is properly working in the French language.
When I select a date, for example August 15, 2012, the DatePicker will display 15 Aoû, 2012 as I would expect. My issue however, is that when the form is posted, the value of the DatePicker is posted as '15 Aoû, 2012' which now needs to be translated on the server before it can be saved properly.
My question is, is there a built-in way inside the jQueryUI DatePicker so that I can have it always post to the server in a consistent format, regardless of which language the control is being displayed in? If there isn't a built-in way, what options exist for achieving this?
I realize that I can change the dateformat to something like 08/15/2012 instead of using the textual representation, however this isn't what I want to do.
There's 2 configuration options for that: altField and altFormat. http://api.jqueryui.com/datepicker/#option-altField
If you specify an altField, that field will be updated too, and will have the altFormat.
Normally you will want make the altField a hidden field, soyou can ignore the regular field and send to db the altField.
As you'll have noticed, supplying a dateFormat works well for newly entered dates, but it does not alter the value attribute which was already supplied to the date input field. It took me some time and I'm not sure whether this solution is ideal, but here's my situation explained and the code which solves it. Might help others with the same problem in the future. In my example I'm using dd/MM/yyyy as the display format.
The page contains any number of date input fields, which may or may not already have a value attribute supplied in the format yyyy-MM-dd, as specified by W3C.
Some browsers will have their own input control to handle dates. At the time of writing, that is for instance Opera and Chrome. These should expect and store a date in the abovementioned format, while rendering them according to the client's regional settings. You probably do not want/need to create a jqueryui datepicker in these browsers.
Browsers which don't have a built-in control to handle date input fields will need the jqueryui datepicker along with an 'alt', invisible field.
The invisible, alt input field with the yyyy-MM-dd format must have the original name and a unique id in order for forms logic to keep working.
Finally, the yyyy-MM-dd value of the display input field must be parsed and replaced with its desired counterpart.
So, here's the code, using Modernizr to detect whether or not the client is able to natively render date input fields.
if (!Modernizr.inputtypes.date) {
$('input[type=date]').each(function (index, element) {
/* Create a hidden clone, which will contain the actual value */
var clone = $(this).clone();
clone.insertAfter(this);
clone.hide();
/* Rename the original field, used to contain the display value */
$(this).attr('id', $(this).attr('id') + '-display');
$(this).attr('name', $(this).attr('name') + '-display');
/* Create the datepicker with the desired display format and alt field */
$(this).datepicker({ dateFormat: "dd/mm/yy", altField: "#" + clone.attr("id"), altFormat: "yy-mm-dd" });
/* Finally, parse the value and change it to the display format */
if ($(this).attr('value')) {
var date = $.datepicker.parseDate("yy-mm-dd", $(this).attr('value'));
$(this).attr('value', $.datepicker.formatDate("dd/mm/yy", date));
}
});
}
<input type="text" name='fieldName' id="datepicker" value="" style="width: 100px;" />
<script type="text/javascript">
$( "#datepicker" ).datepicker( "option", "dateFormat", 'dd/mm/yy' );
$( "#datepicker" ).datepicker();
</script>
It appears someone else had this question or a similar one prior to yours.
If you read this stackoverflow answer, the author was trying to show the date in one format and pass the data to MySQL in another format.
The prior answer in that link gets you set up to access the selected value as a variable. Now all you need is to wire in a parseDate to your selected date variable.
<script type="text/javascript">
$('#cal').datepicker({
dateFormat: 'dd M yy',
onSelect: function(dateText, inst) {
var dateAsString = dateText; //the first parameter of this function
var newDateFormat = $.datepicker.parseDate('dd-mm-yyyy', dateAsString);
}
});
</script>
Check the parseDate link for settings and formatting.
Hope this helps!
Basically, you should not re-format the date. Instead, you should read JavaScript's Date object from Datepicker, via getDate() method. Then, you need to pass it to server.
The question is how. Basically, what you want is some common format. If you use JSON the answer is very simple, just put date object and JSON's stringify() function will automatically format it to ISO8601.
As you may see from Wikipedia, ISO8601 was designed to interchange date and time reliably, therefore that's what you should use.
It might be helpful to know that modern web browsers support Date object's toISOString() method.
As #Pawel-Dyda mentioned,
There's a
getDate() method
var currentDate = $( ".selector" ).datepicker( "getDate" );
Here's an example of what it returns: Wed Jan 20 2016 00:00:00 GMT+0300.
You can parse it in Javascript, PHP, in SQL or whatever.
MySQL parsing examlple:
select str_to_date('Wed Jan 20 2016 00:00:00 GMT+0300','%a %b %d %Y %H:%i:%s');
Returns:
2016-01-20 00:00:00
Solution working for ASP.NET
#using (Html.BeginForm("ActionName", "ControllerName"))
{
#Html.HiddenFor(m => m.DateFrom)
#Html.HiddenFor(m => m.DateTo)
<div class="form-group">
#Html.LabelFor(m => m.DateFrom)
<input id="datepicker-date-from" type="text" class="form-control datepicker" value="#Model.DateFrom.Date.ToString("dd.MM.yyyy")"/>
</div>
<div class="form-group">
#Html.LabelFor(m => m.DateTo)
<input id="datepicker-date-to" type="text" class="form-control datepicker" value="#Model.DateTo.Date.ToString("dd.MM.yyyy")" />
</div>
<input type="submit" class="btn btn-sn btn-primary" value="Download" />
}
#section scripts {
<script type="text/javascript">
$(function () {
$("#datepicker-date-from").datepicker(
{
dateFormat: "dd.mm.yy",
altField: #Html.IdFor(m => m.DateFrom),
altFormat: "yy-mm-dd"
});
$("#datepicker-date-to").datepicker(
{
dateFormat: "dd.mm.yy",
altField: #Html.IdFor(m => m.DateTo),
altFormat: "yy-mm-dd"
});
});
</script>
}

Resources