I'm trying to use the Kendo UI MVC dateTimePicker to format the date unambiguously so that MVC model binding understands it. I have a datetimepicker control in a form which submits via a GET request.
MVC expects dates in this format: yyyy-MM-dd but I want to display dates on the page as dd/MM/yyyy
If I use this code, MVC parses the date correctly, but displays the year first to the user, which isn't what I want:
@(Html.Kendo().DateTimePicker()
.Name("ToDate")
.Format("yyyy-MM-dd")
)
Is there a workaround so I can format the date for humans in the box, but format it in an unambiguous (invariant) format in the URL?
You should configure your DateTimePicker format to a user friendly format. Then use javascript to get the Date object from the widget (not string date). Then format this date object to 'yyyy-mm-dd' and make the request.
So your widget shoul be:
@(Html.Kendo().DateTimePicker()
.Name("ToDate")
.Format("dd/MM/yyyy")
)
Then use this javascript to make the request:
var date = $("#ToDate").data("kendoDateTimePicker").value();
date variable have a javascript date you can format:
function dateToString(date){
var str = date.getFullYear() + "-";
str += ('0' + (date.getMonth() + 1)).slice(-2) + "-";
str += ('0' + date.getDate()).slice(-2) + "T";
str += ('0' + date.getHours()).slice(-2) + "-";
str += ('0' + date.getMinutes()).slice(-2) + "-";
str += ('0' + date.getSeconds()).slice(-2);
return str;
}
This format is "yyyy-mm-dd hh:mm:ss", but you can remove the time part if you want