我正在尝试将字符串变量传递给 JS 日期对象并在将来创建日期。 用这种方式很容易做到:
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var my_date = new Date(year + 1, month +1, day +1);
但是我如何用字符串变量传递它,这样我就可以实现这样的目标:
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var my_variable = 'year + 1, month +1, day +1';
var my_date = new Date(my_variable);
在这种情况下它返回无效的日期
最佳答案
注意
您需要小心处理日期算法,因为它不是对称的并且可能会给出奇怪的结果,例如2016 年 2 月 29 日 + 1 年得到 2017 年 3 月 1 日,而 7 月 31 日减去 1 个月是 7 月 1 日,因为没有 6 月 31 日,它会滚动到 7 月,依此类推。
鉴于您的原始要求,您可能会考虑针对您的特定格式的解析器,例如
function myParse(s, date) {
date = date || new Date();
// Default values object
var values = {
year:{sign:1, value:0}, month:{sign:1, value:0}, day:{sign:1, value:0}
};
// Tokenise string
var part = s.toLowerCase().match(/[a-z]+|\d+|[+-]/ig);
// Process the tokens
if (part) {
for (var i=0, iLen=part.length; i<iLen; i++) {
if (part[i] in values) {
values[part[i]].sign = part[i+1] == '+'? 1 : -1;
values[part[i]].value = +part[i+2];
i += 2;
}
}
}
// Apply to date
date.setFullYear(
date.getFullYear() + values.year.sign * values.year.value,
date.getMonth() + values.month.sign * values.month.value,
date.getDate() + values.day.sign * values.day.value
);
return date;
}
// Examples
var options = {day:'2-digit',month:'short',year:'numeric'};
console.log('Today is ' + (new Date().toLocaleString('en-gb', options)));
['year+1,month+1,day+1', // one of each
'year+2,day+2', // missing parameters
'day + 15, month +2', // any order, random whitespace
'month - 3' // subtraction
].forEach(function(s) {
console.log(s + '\n' + myParse(s).toLocaleString('en-gb', options));
});
它相当宽容,但您应该验证输入。它也可以扩展以处理时间,以及上述月末问题。
关于javascript - 无法将字符串变量传递给 JS 日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52551141/