I need to capture date and time both for my model property. In my model class I have the following
[Required]
[DataType(DataType.DateTime)]
public DateTime?
In my case in my Model I had :
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}", ApplyFormatInEditMode = true)].
In my view in my script, I had:
$(function () {
$('.datepicker').datepicker({
changeMonth: true,
changeYear: true,
format: "dd MMM yyyy"
});
});
When I changed my script's format to format: dd M yyyy
- it worked.
In the model for example:
[Display(Name = "Insert Start Date")]
[Required(ErrorMessage = "You must specify the date of the event!")]
[DataType(DataType.DateTime, ErrorMessage = "Podaj prawidłową datę wydarzenia")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[Display(Name = "Insert End Date")]
[Required(ErrorMessage = "You must specify the date of the event!")]
[DataType(DataType.DateTime, ErrorMessage = "Podaj prawidłową datę wydarzenia")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }
And View my example code:
<script>
$('#startDate').datetimepicker({
onClose: function (dateText, inst) {
var endDateTextBox = $('#endDate');
if (endDateTextBox.val() != '') {
var testStartDate = new Date(dateText);
var testEndDate = new Date(endDateTextBox.val());
if (testStartDate > testEndDate)
endDateTextBox.val(dateText);
}
else {
endDateTextBox.val(dateText);
}
}, dateFormat: 'yy-mm-dd',
onSelect: function (selectedDateTime) {
var start = $(this).datetimepicker('getDate');
$('#endDate').datetimepicker('option', 'minDate', new Date(start.getTime()));
}
}); ....
This caused positive effects: dateFormat: 'yy-mm-dd',
$.validator.addMethod('date', function (value, element) { if (this.optional(element)) { return true; } var valid = true; try { $.datepicker.parseDate('dd/mm/yy', value); } catch (err) { valid = false; } return valid; });
@Html.TextBoxFor(model => model.DOB, new { @class = "datetype", type ="text" })
@Html.ValidationMessageFor(model => model.DOB)
$(function () {
$(".datetype").datepicker({ dateFormat: 'dd/mm/yy' });
});
It works for me.
You need to make sure your application's Culture is properly set.
The following example shows how cultures affect date parsing: https://dotnetfiddle.net/vXQTAZ
DateTime dateValue;
string dateString = "28/05/2015 15:55";
if (DateTime.TryParse(dateString, CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out dateValue))
{
Console.WriteLine("Valid en-US date.");
}
else
{
Console.WriteLine("Not a valid en-US date.");
}
if (DateTime.TryParse(dateString, CultureInfo.CreateSpecificCulture("fr-FR"), DateTimeStyles.None, out dateValue))
{
Console.WriteLine("Valid fr-FR date.");
}
else
{
Console.WriteLine("Not a valid fr-FR date.");
}
Not a valid en-US date.
Valid fr-FR date.
You may also need to make sure that your client side validators are using properly cultures/globalization. If you are using jQuery validate plugin with MVC, see this extension to help modify that plugin to meet your needs: http://blog.icanmakethiswork.io/2012/09/globalize-and-jquery-validate.html
$(function () {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var valid = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
valid = false;
}
return valid;
});
$(".datetype").datepicker({ dateFormat: 'dd/mm/yy' });
});
Put this code in a file datepicker.js and include this file in html
I couln't solve it by the others answers. In my case, using TextBoxFor wasn't mandatory; I used TextBox instead.
Model
[Required(ErrorMessage = "Required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime MyDate{get;set;}
View
@Html.TextBox("MyDate", DateTime.Now.ToString(), new {@type="datetime"})