简体   繁体   中英

How do I get the last day of the selected month in jQuery datepicker?

I want to get the last day of the selected month in jquery datepicker on onSelect

My current code is written below:

  var j = jQuery.noConflict();
  j('.epo-field-date').datepicker({
    dateFormat: "yy-mm-dd",
    minDate: 0,
    maxDate: '1m',
    firstDay: 1,
    onSelect: function(dateText, inst, dateob) {

      var chosen_month = j.datepicker._defaults.monthNames[inst.selectedMonth];
      var chosen_day = date_selected_parts[2];

      j('.chosen-month .month').text(chosen_month);


    }
  });

For example, When I click any day in the month of January, I should be able to return the value 31 or depending on the last day of the selected day of the month.

Any help is greatly appreciated.

You can use $(this).datepicker('getDate'); within the onSelect event to get the selected date as a JavaScript Date .

To get the last day of the month, you can actually advance the month by 1 , and set the day of the month to 0 .

For example, if you wanted the last day in December, JavaScript allows you to fetch the day before January 1 by getting January 0 .

var j = jQuery.noConflict();
j('.epo-field-date').datepicker({
  dateFormat: "yy-mm-dd",
  minDate: 0,
  maxDate: '1m',
  firstDay: 1,
  onSelect: function(dateText, inst, dateob) {

    var selectedDate = $(this).datepicker('getDate');
    var selectedMonth = selectedDate.getMonth();
    var selectedYear = selectedDate.getFullYear();

    var lastDate = new Date(selectedYear, selectedMonth + 1, 0);
    var lastDay = lastDate.getDate();

    //Do something with lastDay

  }
});

An example using today's date:

 var today = new Date(); var month = today.getMonth(); var year = today.getFullYear(); var lastDate = new Date(year, month + 1, 0); var lastDay = lastDate.getDate(); console.log("Last day of the month:", lastDate.toLocaleString()); console.log("Date as number:", lastDay); 

Very simple, You can get selected year, month and create new date to get last date as following code below.

Here sample code for your reference:

<!DOCTYPE html>
<html>
<body>

 <h2>JavaScript new Date()</h2>

 <p id="demo"></p>

 <script>
 var date = new Date();
 var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
 var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

 document.getElementById("demo").innerHTML = lastDay;
 </script>

 </body>
 </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM