简体   繁体   中英

Unable to pass string variable to JS date object

I am trying to pass string variable to JS date object and create date in future. Its easy to do in this way:

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);

But how I can pass it with string variable, so that I can achieve something like this:

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);

In this case it returns Invalid date

Note

You need to be a little careful with date arithmetic since it's not symmetric and may give odd results, eg 29 Feb 2016 + 1 year gives 1 March 2017, and 31 July minus 1 month is 1 July since there is no 31 June, it rolls over to July, and so on.

Given your original requirement, you might consider a parser for your particular format, eg

 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(/[az]+|\\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)); }); 

It's fairly tolerant but you should validate the input. It could be extended to handle time too, and also the end of month issues noted above.

You are inserting Javascript code as a string, which makes no sense to the Date class.

You can have your variables stored in an array to pass them elegantly to Date.

const dates = [year + 1, month +1, day +1]
const my_date = new Date(...dates);

I've read a follow up comment which indicates you'll only be getting strings from wherever you are retrieving the data from. Firstly if the string is in the format of 'year + 1, month + 1, day + 1', it'll never make sense to the Date object. If the string is just 3 numbers separated by a comma, you could split the string at the commas and pass them to the Date object in the same fashion.

const dates = myString.split(',');
const my_date = new Date(...dates);

Unfortunately javascript (and all the languages that I know off hand) do not work like that.

You could use an eval statement instead, which allows you to create the entire instruction as a string and run that string...

var my_variable = 'year + 1, month +1, day +1';
eval('var my_date = new Date(' + my_variable + ');');

HOWEVER using of eval is dangerous, and could open you up to unexpected attacks. Only use it if absolutely necessary, and if you're sure that the string being used is "safe"

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