[英]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
我想在onSelect
jquery datepicker中获取selected
月份的最后一天
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. 例如,当我单击一月中的任何一天时,我应该能够返回值31
或取决于该月所选日期的最后一天。
Any help is greatly appreciated. 任何帮助是极大的赞赏。
You can use $(this).datepicker('getDate');
您可以使用$(this).datepicker('getDate');
within the onSelect
event to get the selected date as a JavaScript Date
. 在onSelect
事件中获取选定的日期作为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
. 要获得该月的最后一天,您实际上可以使该月提前1
,并将该月的某天设置为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
. 例如,如果想要12月的最后一天,JavaScript允许您通过获取January 0
来获取January 0
January 1
日之前的January 1
。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.