Click here to Skip to main content
15,881,380 members
Articles / Web Development / HTML

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

Rate me:
Please Sign up or sign in to vote.
4.90/5 (24 votes)
19 Apr 2017CPOL6 min read 163.9K   4.6K   30   23
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:

C#
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:

Image 1

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

HTML
<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:

C#
@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:

Image 2

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

Image 3

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

Image 4

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:

C#
[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:

Image 5

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

C#
@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:

Image 6

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:

C#
@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:

HTML
<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:

Image 7

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:

Image 8

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

JavaScript
<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:

Image 9

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

C#
[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:

Image 10

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

Image 11

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Bangladesh Bangladesh
A Software Engineer, Passionate Programmer and Technical Writer!!

Comments and Discussions

 
QuestionTime selection Not work for Firefox browser Pin
Member 1453052914-Feb-20 2:49
Member 1453052914-Feb-20 2:49 
Questionhelped resolving Google chrome date picker validation issue Pin
Rabbil15-Apr-18 21:39
Rabbil15-Apr-18 21:39 
QuestionJquery Time Picker.Please replay asap. Its Urgent Pin
pavanichnaga12-Feb-18 20:06
pavanichnaga12-Feb-18 20:06 
PraisedateTimePicker Pin
Member 136577732-Feb-18 1:16
Member 136577732-Feb-18 1:16 
QuestionDattimepicker Pin
Selvakumar Palaniswamy1-Feb-18 20:28
Selvakumar Palaniswamy1-Feb-18 20:28 
QuestionNot displaying calendar Pin
Member 1316030031-Dec-17 7:01
Member 1316030031-Dec-17 7:01 
QuestionCannot get time selections to show Pin
david4life30-Apr-17 11:15
david4life30-Apr-17 11:15 
QuestionDATE FORMAT Pin
M.R.A.17-Apr-17 19:32
M.R.A.17-Apr-17 19:32 
AnswerRe: DATE FORMAT Pin
Tanvir Ahmad Arjel17-Apr-17 23:52
Tanvir Ahmad Arjel17-Apr-17 23:52 
GeneralRe: DATE FORMAT Pin
M.R.A.18-Apr-17 20:47
M.R.A.18-Apr-17 20:47 
Questionhow to select week, and POST AJAX date to server Pin
longnights8-Mar-17 20:26
longnights8-Mar-17 20:26 
Questionwhat about localization Pin
Huanacaraz18-Oct-16 0:14
Huanacaraz18-Oct-16 0:14 
AnswerRe: what about localization Pin
Tanvir Ahmad Arjel18-Oct-16 21:54
Tanvir Ahmad Arjel18-Oct-16 21:54 
QuestionAsp.Net Core Pin
TiredProgrammer12-Oct-16 7:31
TiredProgrammer12-Oct-16 7:31 
AnswerRe: Asp.Net Core Pin
Tanvir Ahmad Arjel12-Oct-16 9:49
Tanvir Ahmad Arjel12-Oct-16 9:49 
PraiseExcellent article Pin
t.alkahtiri12-Oct-16 1:53
t.alkahtiri12-Oct-16 1:53 
GeneralRe: Excellent article Pin
Tanvir Ahmad Arjel12-Oct-16 23:26
Tanvir Ahmad Arjel12-Oct-16 23:26 
GeneralRe: Excellent article Pin
t.alkahtiri15-Oct-16 9:14
t.alkahtiri15-Oct-16 9:14 
QuestionPostback? Pin
Dana Cobb10-Oct-16 6:39
Dana Cobb10-Oct-16 6:39 
Questiongood feature Pin
Member 103987737-Oct-16 7:55
Member 103987737-Oct-16 7:55 
AnswerRe: good feature Pin
Tanvir Ahmad Arjel7-Oct-16 8:05
Tanvir Ahmad Arjel7-Oct-16 8:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.