我正在尝试将选项设置为昨天,今天,明天的日期,我试图在下面的代码中实现其工作,但未显示昨天的日期,我希望选择今天的日期,同时也应该显示昨天的日期和明天日期..该如何实施?任何帮助,将不胜感激。在此先感谢。
<select id= "date-range" class="form-control" name="date">
<option value="yesterday">15th June 2019 (Yesterday) </option>
<option selected value="today">16th June 2019 (Today) </option>
<option value="tomorrow">17th June 2019 (Tomorrow) </option>
</select>
jquery
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var dateRange = document.getElementById('date-range'),
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"];
for(var day = 0; day < 3; day++) {
var date = new Date();
date.setDate(date.getDate() + day);
dateRange.options[dateRange.options.length] = new
Option([date.getDate(), monthNames[date.getMonth()],
date.getFullYear()].join(' '), date.toISOString());
}
});
</script>
答案 0 :(得分:1)
您正在for循环中使用 day 变量将其添加到今天的日期。由于它的开始时间是 0 ,因此永远不会获得昨天的日期。使其从 -1 开始。
要自动选择一个选项,可以使用HTMLOptionElement的 defaultSelected 和 selected 参数并将其设置为true。
最后要找出用户选择了什么,需要将 change 事件监听器附加到select元素。
var dateRange = document.getElementById('date-range'),
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"
];
var days = ["yesterday", "today", "tomorrow"];
for (var day = -1; day < 2; day++) {
var date = new Date();
date.setDate(date.getDate() + day);
var dateAsString = [date.getDate(), monthNames[date.getMonth()],
date.getFullYear()
].join(' ');
if (day == 0) {
dateRange.options[dateRange.options.length] = new
Option(dateAsString, dateAsString + " (" + days[day + 1] + ")", true, true);
} else {
dateRange.options[dateRange.options.length] = new
Option(dateAsString, dateAsString + " (" + days[day + 1] + ")");
}
}
function handleSelected(e) {
console.log(e.target[e.target.selectedIndex].value + " selected");
}
dateRange.addEventListener("change", handleSelected);
<select id="date-range" class="form-control" name="date">
</select>
答案 1 :(得分:0)
You can get as below,
1) Yesterday Date
let now = new Date();
var defaultDate = now - 1000 * 60 * 60 * 24 * 1;
defaultDate = new Date(defaultDate);
2) Today's date
let now = new Date();
var defaultDate = now ;
defaultDate = new Date(defaultDate);
3) Tomorrow's date
let now = new Date();
var defaultDate = now + 1000 * 60 * 60 * 24 * 1;
defaultDate = new Date(defaultDate);
Then you can just format it as per your required one.
Hope this will help you