Javascript: Find Previous Business day

Discussions and Tech Support specific to the iMacros Firefox add-on.
Forum rules
Before asking a question or reporting an issue:
1. Please review the list of FAQ's.
2. Use the search box (at the top of each forum page) to see if a similar problem or question has already been addressed.
3. Try searching the iMacros Wiki - it contains the complete iMacros reference as well as plenty of samples and tutorials.
4. We can respond much faster to your posts if you include the following information: CLICK HERE FOR IMPORTANT INFORMATION TO INCLUDE IN YOUR POST
Post Reply
Posts: 243
Joined: Sun Mar 16, 2008 7:22 am

Javascript: Find Previous Business day

Post by viking » Sun Jun 21, 2020 8:46 am

OK, so this question is maybe a little outside the scope of this forum, but maybe someone can help.

I am trying to write a javascript that outputs the previous business day. For example, if today was Monday 6/15/20 it would return Friday 06/12/20. Saturday 6/13/20 and Sunday 6/14/20 would also return Friday 06/12/20. Any other days of the week would return the previous day.
My javascript below works fine as long as there are no holidays involved:

WORKING SCRIPT (without Holidays)

Code: Select all

var today = new Date();
var dayOfWeek=today.getDay();
var subtractDays=1;
if (dayOfWeek==0) {subtractDays=2;} // Sunday, use Friday (any other day use previous day)
if (dayOfWeek==1) {subtractDays=3;} // Monday, use Friday (any other day use previous day)

var lastBSNDay = new Date(); 
lastBSNDay.setDate(today.getDate() - subtractDays);
var day = lastBSNDay.getDate().toString(); 
if (day.length < 2) {day = "0" + day;} 
var month = (lastBSNDay.getMonth() + 1).toString(); 
if (month.length < 2) {month = "0" + month;} 
var year = lastBSNDay.getFullYear().toString(); 
var lastBSNDayString = month+ "/" + day + "/" + year; 
iimDisplay("Last BSN day = "+lastBSNDayString);

How would I write a javascript that take into account holidays? I found this code online ( ... -moment-js):

Code: Select all

function getPreviousWorkday() {
  return [1, 2, 3, 4, 5].indexOf(moment().subtract(1, 'day').day()) > -1 ? 
    moment().subtract(1, 'day') : moment(moment().day(-2));
and "documentation" for moment.js is here:
How would I use this in an iMacros javascript? If not possible, is there some other way?

iMacros v8.9.7
Firefox v52.8.1
WIN7 x64
Posts: 243
Joined: Sun Mar 16, 2008 7:22 am

Re: Javascript: Find Previous Business day

Post by viking » Mon Jun 22, 2020 3:26 am

No need to respond. I have almost solved it with help of some code on the web.

However, it would be very useful to learn how to use the moment.js library ( ... moment-js/) in an iMacros javascript. (I posted this question as a follow up to an old post here: viewtopic.php?f=11&t=18247&start=15)
Post Reply