Branching & Filtering by Time (Custom Code)

Sometimes you’d like to branch workflows or filter records based on time-related conditions - like whether it’s after business hours :three_o_clock: which day of the week / day within a month it is :spiral_calendar:.

To support this, I tested a custom-coded workflow action that

  • Extracts: Year, month, day, hour and/or weekday
  • Calculates: Day type (weekday or weekend) & outside business hours flag (true/false)

Preparations

1. Register your access token as a secret in the custom code action to fetch your portal’s timezone.

  • Here’s how to create a private app to generate access token

2. Properties to include:

  • custom_date: the date or date/time you’dl ike to extract day/month from or you’d like to cehck if it’s a within business hour or on the weekends

3. Data Output

  • month, day, hour (Number)
  • day_type (Enumeration - e.g. weekday or weekend)
  • outside_business_hours (Single checkbox / Enumeration)

4. (Optional) Create properties that match the field types above.

  • If you only need the generated values inside the same workflow, you don’t need to have the properties.
  • If you want to use them elsewhere (e.g., in lists, reports, or other workflows), you’ll need properties to store the values. In this case, please make sure to add an “Edit Record” action after your custom code, and map the generated values to a property of your choice.

Codes for the action

const axios = require('axios');

exports.main = async (event, callback) => {

 const accessToken = process.env.SECRET_NAME; // Replace with your secret name
 const customDateRaw = event.inputFields['custom_date'];
 console.log("🔍 Raw date input (ms):", customDateRaw);

 if (!customDateRaw) {
 console.error("❌ No date input found.");
 return callback({ outputFields: {} });
 }

 // STEP 1 - Get Portal's IANA Timezone
 /*
 Fetches the timezone setting from HubSpot's account settings.
 Reference: https://developers.hubspot.com/docs/guides/api/settings/account-information-api
 */
 let portalTimezone;
 try {
 const resp = await axios.get('https://api.hubapi.com/account-info/v3/details', {
 headers: {
 'Authorization': `Bearer ${accessToken}`,
 'Content-Type': 'application/json'
 }
 });
 portalTimezone = resp.data.timeZone;
 console.log("🌐 Portal Timezone:", portalTimezone);
 } catch (error) {
 console.error("❌ Error fetching portal timezone:", error?.response?.data || error.message);
 return callback({ outputFields: {} });
 }

 // STEP 2 - Parse the timestamp from input
 const dateObj = new Date(Number(customDateRaw));
 if (isNaN(dateObj.getTime())) {
 console.error("❌ Invalid Date:", customDateRaw);
 return callback({ outputFields: {} });
 }
 console.log("📅 Parsed Date Object (UTC base):", dateObj.toISOString());

 // STEP 3 - Extract local date/time parts in portal's timezone
 const formatter = new Intl.DateTimeFormat('en-US', {
 timeZone: portalTimezone,
 year: 'numeric',
 month: 'numeric',
 day: 'numeric',
 weekday: 'long',
 hour: 'numeric',
 hour12: false
 });

 const parts = formatter.formatToParts(dateObj);
 const getPart = (type) => parts.find(p => p.type === type)?.value;

 const year = Number(getPart('year'));
 const month = Number(getPart('month'));
 const day = Number(getPart('day'));
 const hour = Number(getPart('hour'));
 const weekday = getPart('weekday');

 console.log("🧩 Local Date Parts:", { year, month, day, hour, weekday });

 // STEP 4 - Apply business rules
 /*
 Checks whether the date falls on a weekend, or outside business hours.
 Business hours: 9:00 - 17:59 (portal local time).
 */
 const isWeekend = (weekday === "Saturday" || weekday === "Sunday");
 const outsideBusinessHours = isWeekend || hour < 9 || hour >= 18;
 const dayType = isWeekend ? "weekend" : "weekday";

 console.log("⏰ Outside Business Hours:", outsideBusinessHours);
 console.log("📅 Day Type:", dayType);

 // STEP 5 - Return extracted values
 callback({
 outputFields: {
 year: year,
 month: month,
 day: day,
 hour: hour,
 weekday: weekday,
 outside_business_hours: outsideBusinessHours,
 day_type: dayType
 }
 });
};

console.log("End of Action")

Thanks for sharing @halice :raising_hands:

You can also not use custom code and use something easy like:
Format Data
Where you can just trigger the workflow and then format the last modified date property on the specific record to the date/time you want to look at :raising_hands:

Great point @MHolzer :light_bulb:— Jaycee

Sorry for the delay — I missed the notification.

And thank you for the advice :slightly_smiling_face:

I was able to save the time as a string by using **Format date and time** in **custom** mode to output it as text.
For example: `format_datetime([hs_timestamp], ‘H’, ‘UTC+9’, ‘jp’)`

I also looked at **Subtract an amount of time**, but even if I set it to subtract 0, the available outputs still seem to be only date or datetime.

So if you need to output it as an integer in order to use number-relaeted filters like “is more /less than” in a branch, I think we might still need to use a custom-coded action?