This JavaScript code creates a date picker with the ability to select the current date. It disables the current date after noon if it’s the 1st or 15th of the month. This functionality helps users select dates efficiently.
You can use this code in web applications requiring date selection. It simplifies date picking for users. Its current date feature enhances user experience.
How to Create Date Picker with current date Using JavaScript
1. First of all, load the Bootstrap, Bootstrap Datepicker CSS, and jQuery UI by adding the following CDN links into the head tag of your webpage.
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker.css'> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css'>
2. Create an input field with an ID, such as <input id="startDate">
, where the date picker will be attached.
<input type="text" id="startDate" name="startDate">
3. Now, load the jQuery, Bootstrap JS, and jQuery UI JS by adding the following scripts before closing the body tag:
<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js'></script>
4. Finally, incorporate the following JavaScript code within a <script>
tag in your HTML file. Ensure that it is placed after the inclusion of jQuery and jQuery UI libraries.
$(function () { //var dateToday = new Date(); $('#startDate').datepicker().datepicker(); $('#startDate').datepicker('option', 'minDate', mdate()); function mdate(){ // If current date is 1st or 15th & after 12:00pm disable current date var startDate = new Date(), returnVal = 0, dateToday = new Date(), getDate = dateToday.getDate(), getHour = dateToday.getHours(); if(getHour >= 12 && getDate == 1) { startDate.setDate(dateToday.getDate() + 14) } else if (getHour >= 12 && getDate == 15) { startDate.setMonth(dateToday.getMonth() + 1, 1); } else if (getHour < 12 && getDate == 13) { startDate.setMonth(dateToday.getMonth() + 1, 1); } else { } return startDate; } });
You can customize the behavior of the date picker according to your requirements by modifying the mdate()
function. This function currently disables the current date after 12:00 PM on the 1st and 15th of each month. Adjust the conditions inside this function to suit your needs.
That’s all! hopefully, you have successfully created a Date Picker with the current date. If you have any questions or suggestions, feel free to comment below.