Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simplest Way to Use JQuery Date Picker and Date Time Picker in ASP.NET/ASP.NET MVC

0.00/5 (No votes)
19 Apr 2017 3  
This is the simplest way to use JQuery Date Picker and Date Time Picker in ASP.NET/ASP.NET MVC with many customization according to your requirement.

[Update Message]

First I wrote the article only on jQuery Date Picker .But later I realised that sometimes we are in need of Time Picker also along with Date Picker and that's why i have modified the article and added Time Picker option also along with date picker.

Introduction

Sometimes, we are in a situation where we need to allow user/users to input various kinds of dates such Date of Birth, Joining Date, Received Date, Departure Date and many more. But it is a bad practice to render a simple text box for entering date value as there is a format issue of the date. Suppose if I do so, then some users will enter the date in MM/dd/yyyy format, some users will in dd-MMM-yyyy format, some others will in yyyy/MM/dd format and so on. As consequence, the whole thing will be a farrago. So it is always best practice to render a Date Picker/Calendar to the users to pick the date where a common date format will be maintained for all users.

Let's Start

Suppose we have an Employee form where we will input the employee's information. In the Employee form, there is a field named "Joining Date" which is used to input the Employee's Joining Date. Here, we will use jQuery Date Picker for Joining Date value input.

Step 1: Our model class will look like follows:

public class Employee
    {
        public int Id { get; set; }

        [Display(Name = "Employee Name")]
        public string EmployeeName { get; set; }

        [Display(Name = "Joining Date")]
        public DateTime JoiningDate { get; set; }
    }

Step 2: First of all, we need to install JQueryUI packages using NuGet Packages Manager in our project as follows:

Step 3: Now add the following CSS and JavaScript files links to the views. In this case these are Create.cshtml and Edit.cshtml.

<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>

Step 4: Now add a class (html class attribute, not Model class!) or id name to the JoiningDate editor html which renders the input field for JoiningDate value input. In this case, here I have added a class attribute and it looks like follows:

@Html.EditorFor(model => model.JoiningDate, 
new { htmlAttributes = new { @class = "form-control date-picker" } })

Step 5: Now call the JQuery datepicker() function which will be invoked whenever user clicks on the Joining Date input field. And it should look like follows:

<script src="~/Scripts/jquery-3.1.1.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $(".date-picker").datepicker({
                dateFormat: 'dd-M-yy' 
            });

        });

    </script>

This will take input as "19-Apr-2017" Format. If you want it as "19/04/2017" the use "dd/mm/yy" instead of "dd-M-yy".For more detail about formatting input date in jquery date picker : http://api.jqueryui.com/datepicker/#option-dateFormat

Now run the project to create a new Employee record. Whenever you are clicking on the Joining Date input field to input the Joining Date value, it is presenting a JQuery Date Picker/Calendar to pick the date as follows:

After creating a record with Employee Name Mark, it is displayed as follows:

And if you want to Edit/Update the Joining Date of the Mark record, then it appears as follows:

Although it is working as expected, but there is a slight problem in date formatting. The date is shown with unnecessary time value. It should not be shown. To remove the unnecessary time value and format the date correctly,we have to use Data Annotation as follows:

[Display(Name = "Joining Date")]
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime JoiningDate { get; set; }

Now run the project and see the date format has been changed and it is displaying without the unnecessary time value both in Display and Edit field as follows:

Moreover, to highlight the existing value of the Joining Date in the Edit field, Rewrite in the @Html.EditorFor() helper method as follows:

@Html.EditorFor(model => model.JoiningDate, new { htmlAttributes = new { Value = Model.JoiningDate.ToString("dd-MMM-yyyy"), @class = "form-control date-picker"} })

Now its showing as follows with highlighting the existing Joining Date in Blue Color:

Till now, that's pretty good. But remember that although we are presenting a calendar to pick the date from that calendar, still user is able to insert value in the Date input field without picking it from the calendar, which should not be allowed. User should only be allowed to pick the Date value from the calendar to maintain the date formatting integrity.

To prevent the user from writing or pasting anything in the Joining Date input field, add the some HTML atrributes to the @Html.EditorFor() helper method and the code will look like as follows:

@Html.EditorFor(model => model.JoiningDate, new { htmlAttributes = new { Value = Model.JoiningDate.ToString("dd-MMM-yyyy"), @class = "form-control date-picker", onkeydown = "return false", onpaste = "return false" } })

Now the user will not be able to write or paste anything in the input field of the Joining Date, rather he/she has to pick the Date value from the Date Picker/Calendar.

Although everything is working fine, there is a small inflexibility with our JQuery Date Picker/Calendar. Suppose user is to pick a date of 10 or 15 years back, then he/she has to go back month by month by clicking the back button on the Date Picker/Calendar header. Now think if she/he is to pick a date of 10 years back, then she/he has to click 12*10 = 120 times on the back button.

So there should be a Month dropdown menu and Year dropdown menu in the Date Picker/Calendar header from where user would be able to pick any year and month that will present in the Date Picker/Calendar. To do so, we have to add some customizing options in the datepicker() function as follows:

<script src="~/Scripts/jquery-3.1.1.min.js"></script>

<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $(".date-picker").datepicker({
                changeMonth: true,
                changeYear: true,
                yearRange: "-100:+0", // You can set the year range as per as your need
                dateFormat: 'dd-M-yy'
            });
        });
    </script>

Now run the project and click on the input field of the Joining Date property while creating a new Employee record or update any existing record. And see now you are able to pick any date from last 100 years easily as follows:

A Google chrome and jquery.validate.js issue!!

Sometimes Google Chrome goes wild!! It throws a validation error message stating "The field Date must be a date." even the input value is a date in correct format. According to some StackOverFlow questions and answers it is a jquery.validate.js bug. To fix this issue, need to write some javascript code as follows:

<script src="~/Scripts/jquery-3.1.1.min.js"></script>

<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>

<script type="text/javascript">
        $(document).ready(function () {
            $(function () {
                $(".date-picker").datetimepicker({
                    changeMonth: true,
                    changeYear: true,
                    yearRange: "-100:+0",
                    dateFormat: 'dd-M-yy'
                });

            });

            jQuery.validator.methods.date = function (value, element) {
                var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
                if (isChrome) {
                    var d = new Date();
                    return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
                } else {
                    return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
                }
            };

        });

    </script>

That's all about JQuery Date Picker!!

Now Adding Jquery Time Picker along with JQuery Date Picker

Adding Jquery Time Picker along with the existing date picker is a fun!! Its very simple to implement.

Step 1: Install Jquery Time Picker Addon package using NuGet Packages Manager in the project as follows:

Step 2: Now add the following CSS and JavaScript files links to the views. In this case, views are Create.cshtml and Edit.cshtml.

<link href="~/Content/jquery-ui-timepicker-addon.min.css" rel="stylesheet" />

<script src="~/Scripts/jquery-ui-timepicker-addon.min.js"></script>

Step 3: Change the datepicker() function name to datetimepicker() with some options as follows:

<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
    <script src="~/Scripts/jquery-ui-timepicker-addon.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(function () {
                $(".date-picker").datetimepicker({
                    changeMonth: true,
                    changeYear: true,
                    yearRange: "-100:+0",
                    dateFormat: 'dd-M-yy',
                    controlType: 'select',
                    timeFormat: 'hh:mm TT'
                });

            });

            jQuery.validator.methods.date = function (value, element) {
                var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
                if (isChrome) {
                    var d = new Date();
                    return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
                } else {
                    return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
                }
            };

        });

    </script>

Done! Now run the project to create a new Employee record. Whenever you are clicking on the Joining Date input field to input the Joining Date and Time value, it is presenting a JQueryDateTimePicker to pick the date and time as follows:

Step 4: Now to Display the time along with date, Modify the [DisplayFormat()] Data Annotation in Employee Model Class as Follows:

[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy hh:mm tt}", ApplyFormatInEditMode = true)]
public DateTime JoiningDate { get; set; }

After creating a record with Employee Name Mayanti, it will be displayed as follows:

And if you want to Edit/Update the Joining Date of the Mayanti record, then it appears as follows:

That's all about JQuery Date Picker and JQuery Date Time Picker!!

Conclusion

You can also customize JQuery Date Picker and JQuery Date Time Picker further more as per as your requirement by taking help from the JQuery UI and JQuery Date Time Picker official websites.

Don't forget to comment if you have any suggestion or query. Moreover you are requested to share if it benefits you. Thank you!!

Suggestion: Downloading the source codes will help more to understand the article easily.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here