对于这种情况,我不想使用 jQuery 日期时间选择器。因为我制作移动应用程序。
[我的案例]我正在使用 javascript 来获取今天和接下来几天的日期的值。但我想要更灵活,希望使用 jquery 将数据显示在双循环上并显示到组合框中。
直到今天,我使用以下方式获取数据:
function GetDay(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = yyyy+'-'+mm+'-'+dd;
alert(today);
}
Result : 2013-04-28
对于我来说第二天使用:
function NextDay1(){
var today = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} next1 = yyyy+'-'+mm+'-'+dd;
alert(next1);
}
Result : 2013-04-29
我使用的方式是非常手动的,如果我想获取数据:
2013-04-28
2013-04-29
2013-04-30
2013-05-01
2013-05-02
ect...
我使用的方式是非常手动的,如果我想获取这样的数据并放置一个组合框来选择该日期?
最佳答案
您可以像这样循环获取日期:
// Create an empty array to store the dates generated
var myDates = [];
// Loop through for 5 times here
for (var i = 0; i < 5; i++) {
var myDate = new Date();
var fullDate = new Date(myDate.setDate(myDate.getDate() + i));
var twoDigitMonth = ((fullDate.getMonth().length + 1) === 1) ? (fullDate.getMonth() + 1) : '0' + (fullDate.getMonth() + 1);
var twoDigitDates = ('0' + fullDate.getDate()).slice(-2);
var currentDate = fullDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDates;
myDates.push(currentDate);
}
// Check the dates in console as an array
console.log(myDates);
然后插入到下拉列表中,例如:
// Loop through the date array we have created
$.each(myDates, function (index, item) {
// Add options to the select list
$('#mySelect').append($('<option>', {
value: index,
text: item
}));
});
关于Javascript 获取日期并循环到组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16262591/