Tip: Adding Days to a date using an input dialogue

A tip for anyone trying to add a variable number of days to a date through a dialogue.

var days=plugins.dialogs.showInputDialog( 'Download Appointments',  'Number of Days Ahead to Download', 3);

if (days>7){
plugins.dialogs.showWarningDialog( 'Warning',  'You can only download up to 7 days ahead',  'OK')
var days=7
}

var d=new Date();
d.setDate(new Date().getDate()+days);

Whilst the warning script measuring days greater than seven treats ‘days’ as a number and works. The date statement d.setDate doesn’t see the variable as a number but as text, unlike the if statement.

One of those things you puzzle over as to why its not working for a few hours, pulling a few more hairs out!!

Anyway that answer is to simple do a string to num conversion:

var days=utils.stringToNumber(days)

before running the date statement.

Hi David,

Thanks for this tip!
You can also optimize the code a bit by not declaring the days variable again and you don’t need to create a new date twice.
And you can use the stringToNumber() function straight in the setDate() function.

var days = plugins.dialogs.showInputDialog( 'Download Appointments',  'Number of Days Ahead to Download', 3);
if ( days > 7 ) {	
	plugins.dialogs.showWarningDialog( 'Warning',  'You can only download up to 7 days ahead',  'OK') 
	days = 7; 
} 
var d=new Date(); 
d.setDate(d.getDate() + utils.stringToNumber(days));

Hope this helps.

Thanks Robert.

David

dpearce:
Whilst the warning script measuring days greater than seven treats ‘days’ as a number and works. The date statement d.setDate doesn’t see the variable as a number but as text, unlike the if statement.

One of those things you puzzle over as to why its not working for a few hours, pulling a few more hairs out!!

Anyway that answer is to simple do a string to num conversion:

var days=utils.stringToNumber(days)

I’m also missing some hair from the first time I ran into this Javascript typing irregularity. “Looks like chicken, tastes like chicken, why isn’t it chicken?!? $&^%!”

Anyway, in the days before the utility functions we would add zero to a value to force the value to numeric (ex: ‘3’ + 0).

you still need to use this technique to force a numeric to a string on the occasion when the reverse situation happens. in this case add an empty string to a value to force the string type (ex: 3 + ‘’).