Search code examples
jquerybootstrap-datepicker

Get the start and end dates visible in a datepicker days view?


I am using bootstrap datepicker

I wanna get the first and the last dates in the calendar.

enter image description here

How can I get those dates?


Solution

  • There is no any in-built option/method to get the dates what you have asked. But the following approach gives you those dates.

    Approach : Get the current month, subtract it by the number of .old days to get the starting date or add the number of .new days to get the end date.

    It works even if the weekStart is option is changed.

    var startdate = document.getElementById("startdate");
    var enddate = document.getElementById("enddate");
    
    $("#date").datepicker('update', new Date()).on("show",function(date){
        var date = new Date($(this).data("datepicker").getDate());
        var startofmonth = new Date(date.getFullYear(), date.getMonth(),1);
        var endofmonth = new Date(date.getFullYear(), date.getMonth()+1, 0);
        startofmonth.setDate(startofmonth.getDate()-$(".datepicker .old.day").length);
        endofmonth.setDate(endofmonth.getDate()+$(".datepicker .new.day").length);
        startdate.textContent = "Start : "+startofmonth;
        enddate.textContent = "End : "+endofmonth;
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/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>
    <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"/>
    
    <span id="startdate">Start : </span><br>
    <span id="enddate">End : </span><br>
    <input id="date">

    Note: If you are using other locales instead of en, then replace the first line in the show method by the following lines.

    var language = $("#date").data("datepicker").o.language;
    var months = $.fn.datepicker.dates[language].months;
    var view = document.querySelector(".datepicker-days .datepicker-switch").textContent.split(" ");
    var date = new Date(view[1],months.indexOf(view[0]),1);
    

    Update on Why addition/subtraction by dayOfWeek to start/end dates shouldn't be used to get the result (Must read):

    1. The datepicker always has 7 columns(as intended) and 6 rows(constant). For instance, take the month May, 2019, it has 31 days and need only 5 rows in the calendar, but 6 rows are displayed, including the next month's dates. Here the addition/subtraction won't work.

    2. If weekStart is changed, weekStart must be taken into consideration while addition/subtraction by day.